For Loops

A for loop is used when the number of iterations is known in advance.

Here is an example of a program containing a for loop:

program ForLoop;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  i: integer;
begin
  for i := 170 to 190 do
    begin
      write('Character number ', i, ' is ');
      writeln(Chr(i), '.');
    end;
  readln;
end.

The stepper variable i is also called a control variable. Occasionally it is preferable to decrement the stepper variable, which requires the use of the keyword downto instead of to. The following program prints out the letters of the alphabet in reverse order. (As a mental exercise, try reciting the alphabet backwards before running the program).

program ReverseAlphabet;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  i: integer;
begin
  for i := 26 downto 1 do
    begin
      write(chr(i + 64), ' ');
    end;
  readln;
end.
Features introduced:
  • The for loop

  • Chr function for giving the letter corresponding to its ASCII code number

  • Use of i as a stepper variable (j and k are also acceptable).

  • Use of downto in for loop to count down
Programming - a skill for life!

Iteration: for loops, repeat loops and while loops