For Statement
The for
statement implements an iterative loop and requires you to specify the number of iterations. The syntax of the for
statement is:
for counter := initial_value to final_value do statement_list // or for counter := initial_value downto final_value do statement_list
counter
is a variable which increments (or decrements if you use downto
) with each iteration of the loop. Before the first iteration, counter
is set to initial_value
and will increment (or decrement) until it reaches final_value
.
final_value
will be recalculated each time the loop is reentered.
This way number of loop iterations can be changed inside the loop by changing final_value
. With each iteration, statement_list
will be executed.
initial_value
and final_value
should be expressions compatible with counter
.
If final_value
is a complex expression whose value can not be calculated in compile time and number of loop iterations is not to be changed inside the loop by the means of final_value
, it should be calculated outside the for statement and result should be passed as for statement's final_value
.
statement_list
is a list of statements that do not change the value of counter. If statement_list
contains more than one statement, statements must be enclosed within begin-end
block.
Here is an example of calculating scalar product of two vectors, a
and b
, of length 10
, using the for
statement:
s := 0; for i := 0 to 9 do s := s + a[i] * b[i];
Endless Loop
The for
statement results in an endless loop if final_value
equals or exceeds the range of the counter
’s type.
More legible way to create an endless loop in Pascal is to use the statement while TRUE do
.
What do you think about this topic ? Send us feedback!