Factorial in Pascal - iteratively

 <<algorithm

Factorial iteratively

program fact_iter;
var n,s,i: integer;
begin
  write('n = ');
  readln(n);
  i:=1;
  s:=1;
  while i<=n do begin
    s:=s*i;
    i:=i+1;
  end;
  writeln(n,'! = ',s);
  readln;
end. 

 

 The first line of the program can be treated as an ornament, but required by the syntax of the language pascal. Every program in the pascal must start with the keyword program preceding the name of the program, it adds nothing to the implementation of the algorithm. The second line is auxiliary. We know that our algorithm uses three variables that store integers. In the pascal, all variables must be declared before the block of code starts. When declaring a variable, we must specify what type of data will be stored in it.

 The third line containing the keyword begin corresponds to the starting block (1) of our algorithm.

 Lines 4 through 5 perform an input/output operation (2) in which the input data is taken - the number for which we want to calculate the value of the function factorial.

 In line 6, we give the initial value of the auxiliary variable i, numbering the successive steps of the iterative loop of our algorithm, and in line 7 we assign the initial value 1 to variable s. Lines 6-7 follow the step (3) of the algorithm.

 The while statement is equivalent to the selection block (4) from our algorithm. Instructions contained in lines 9 - 10 (block 5) will be executed as long as the condition in the while statement is satisfied, i.e. until i is less than or equal to n. If constantly increasing and becomes greater than n, we pass to the instruction after the while loop, starting in line 12, in which the result is printed (6).

 The readln statement on line 13 has nothing to do with the execution of the implementation of the algorithm. It serves to stop the program until you press the enter key, which prevents the program window from closing immediately.

 Instruction end. from line 14 ends the program (block of the end of the algorithm (7)).