For..Do

Description

The "For..Do" loop is an iterative construct that is most useful when the number of times to loop is known and a counting index value is needed. The syntax of the "For..Do" loop is:

For <local variable> := <expression> <to or downto > <expression> do 
  <statement>;

The local variable after the "For" keyword will contain successive values during the execution of the loops. This variable must be defined in the procedure or function using this construct so that the value is private an not subject to being assigned by some other concurrent routine that might also use a variable with the same name. The first value it will contain is the value in the first numerical expression after the assign- ment. After each execution of the following statement this variable will be incremented by one. The iteration continues while the local variables value is less than or equal to the second numeric expression.

Examples

This example shows the values 1 through 10:


which produces this:


if "downto" is used instead of "to" then the counter is decremented to the final value instead of incremented:


which produces this:


In a manner similar to the IF construct if more than one statement needs to execute enclose that group of statements in a begin..end compound statement.

The loop statements occur while the index variable is approaching or equal to the final value. This check is done at the top of the loop. This means there are values that could cause the loop statements to be skipped entirely. For example, the following loop statement will never be executed:

for scanner:=1 to -1 do
  Prompter.Writeln(‘This will never write’);

Setting up explicit numeric bounds such as this would probably never occur. However the following it is common to be iterating over information where the number of items might be zero. In this case it is convenient for the loop statements to be skipped:

for Index:=1 to NumberOfValidDataPoints do
  List.Writeln(Buffer[Index])

Although it is possible to assign a loop index variable inside the ?loop with the loop statements this is considered very bad style since it breaks the abstraction of the loop body looping a specific number of times. If the number of loops is not known and fixed prior to the loop starting then an alternative looping construct designed to terminate on a condition should be used instead.