When we want to execute a sequence of instructions a specific number of times, it is possible to set up and use one of the basic loops, such as the while-do below. Before the loop is begun, the counter called num is initialized to the first value desired. The loop itself consists of five statements: (1) the reserved words WHILE and DO to indicate the sort of loop along with a conditional statement which dictates if the body of the loop is to be executed; (2) the reserved word BEGIN which indicates the start of the body; (3) a statement to print the value of num; (4) an assignment statement to increment the value of num by one; and (5) the reserved word END to indicate the end.
{ Print the first five Natural numbers }
num := 1;
WHILE num <= 5 DO
BEGIN
writeln(num);
num := num + 1
END
For a situation such as this, Pascal provides a programming short-cut known as the for loop. The one following performs the same task as the loop above, but uses only two lines of code.
FOR num := 1 TO 5 DO writeln(num)
The for statement specifies both the initialization of the counter and the maximum value that it may have during the execution of the loop. In Pascal, the for statement also checks to make sure the value of the counter does not exceed the maximum value. Thus, the body of the following loop will not be executed at all.
FOR num := 5 TO 1 DO writeln(num)
The above for loop uses the default increment of one. If the desired values are not consecutive, code can be written to generate them if the difference between them is calculable. The next segment calculates and prints even numbers using related Natural numbers in the counter. Notice that since more than one statement needs to be repeated, they are bounded by the reserved words BEGIN and END.
{ Print the first five even Natural numbers }
FOR i := 1 TO 5 DO
BEGIN
num := i * 2;
writeln(num)
END
The for loop can use any ordinal type as the "loop control variable". Since the letters of the alphabet occur in order in ASCII code, it is possible to have a variable contain one after another as shown in the code below. Executing this loop will result in ABCDEFGHIJKLM being printed on a single line.
FOR letter := 'A' TO 'M' DO write(letter); writeln
N.B. This code will not work if the computer is utilizing EBCDIC character encoding.
It is also possible to use a negative increment (i.e., decrement) using the reserved word DOWNTO.
{ Print the first five odd Natural numbers backwards }
FOR i := 5 DOWNTO 1 DO
BEGIN
num := i * 2 - 1;
writeln(num)
END