While Loops

A while loop tests a condition at the start of a loop and only continues while the condition is true. If the condition is false at the outset then the rest of the code in the loop will not be executed at all.

The program WhileLoop performs the same validation function as the program RepeatLoop. Note the way that we had to change the condition to be tested. Also, the two lines of code inside the loop must now also be used before the loop.

program WhileLoop;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Num : integer;
begin
  write('Enter an integer between 2 and 12 ');
  readln(Num);
  while (Num < 2) or (Num > 12) do
    begin
      write('Enter an integer between 2 and 12 ');
      readln(Num);
    end;
  writeln(Num, ' is acceptable.');
  readln;
end.

The next program calculates factorials. For example, 6 factorial (also written 6!) requires the calculation of 6 x 5 x 4 x 3 x 2 x 1

program Factorial;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  InputNum, i  : integer;
  Fact : int64;
begin
  Fact := 1;
  write('Please enter an integer in the range 1 to 20 to find its factorial. ');
  readln(InputNum);
  i := InputNum;
  while i > 1 do
  begin
    Fact := Fact * i;
    dec(i);
  end;
  writeln(InputNum, '! = ', Fact);
  readln;
end.
Features introduced:
  • The use of the type int64 to use 64 bits to store a whole number

  • A while loop, which will not be carried out if the integer entered is 1

  • Use of the dec function to decrement an ordinal instead of using i := i - 1

    (An ordinal number is a number denoting a place in an ordered sequence. Integers are ordinals.)

Programming - a skill for life!

Iteration: for loops, repeat loops and while loops