next up previous contents index
Next: While and Repeat Up: Control Structures Previous: The If Instruction

The For Instruction

The for instruction is a control structure to repeat a block, a fixed number of times. The most general appearance is:

for ASSIGNMENT to EXPRESSION do BLOCK endfor

A counter for the for repetitions of the block is needed. This is a variable which counts the loop iterations. The value is increased by one if an loop iteration is completed. If the value of the counter is larger then the value of the EXPRESSIONS, the BLOCK won't be executed anymore. If the value is already larger at the beginning, the instructions contained in the block are not executed at all. The counter is a simple variable. A for instruction could look like this:

for i := 2 to 5 do print (" here we are: ",i) endfor

produces:

here we are: 2
here we are: 3
here we are: 4
here we are: 5

It is possible to control the repetitions of a block by assigning a value to the counter or by using the continue, break instructions. The instruction break leaves the cycle immediately while continue increases the counter by one and performs another repetition of the block. One example could be:

for counter := 1 to 200 do
a := a * counter
c := c + 1
if test == TRUE then break endif
endfor

In this example the boolean variable test is used to abort the repetitions of the block early.



Niels.Mache@informatik.uni-stuttgart.de
Tue Nov 28 10:30:44 MET 1995