Factorial - iterative algorithm

 

  The factorial of the natural number n is called the product of all natural numbers from 1 to n. The factorial of n is n! (n with an exclamation mark). 0! by definition it is equal to 1. For example:

1! = 1

2! = 1 * 2 = 2

3! = 1 * 2 * 3 = 6

4! = 1 * 2 * 3 * 4 = 24

5! = 1 * 2 * 3 * 4 * 5 = 120

In General, we can write:
 
n! = 1 * 2 * ... * (n-1) * n
 
 The direct representation of this definition is presented below in the form of a flowchart iterative algorithm to compute the factorial function values.
 

 
Factorial iteratively
Implementation of the algorithm in:Pascal, C++, Java, Python, JavaScript

Description of the algorithm:

  1. Start - our algorithm starts here.
  2. We load input data - a natural number n, which is an argument to the function factorial.
  3. We initiate two auxiliary variables:
    i - it will accept subsequent natural values from 1 (this value is initially set) to n,
    s - in this variable the value of the product of consecutive natural numbers is stored, we start from 1.
  4. We check if the value of variable i is less than or equal to n. If the condition from point 4 is satisfied, we multiply the value s of the product of the numbers by i. Then we increase the value of the variable i by 1, that is, we move to the next natural number and return to point 4 of the algorithm. Points 4-5 will be executed as long as the value of the variable i exceed the value stored in the variable n.
  5. After calculating the product of consecutive natural numbers from 1 to n, we print the result contained in the variable s.
  6. Stop - end of the algorithm.