FOR
loop
If you want to write a program to print the numbers one to 100 you can either type each number and wear out your fingers, or you can use a single variable and a small FOR
loop.
Try compiling this E program (the space after the `\d' in the string is needed to separate the printed numbers):
PROC main() DEF x FOR x:=1 TO 100 WriteF('\d ', x) ENDFOR WriteF('\n') ENDPROC
When you run this you'll get all the numbers from one to 100 printed, just like we wanted.
It works by using the (local) variable x
to hold the number to be printed.
The FOR
loop starts off by setting the value of x
to one (the bit that looks like an assignment).
Then the statements between the FOR
and ENDFOR
lines are executed (so the value of x
gets printed).
When the program reaches the ENDFOR
it increments x
and checks to see if it is bigger than 100 (the limit we set with the TO
part).
If it is, the loop is finished and the statements after the ENDFOR
are executed.
If, however, it wasn't bigger than 100, the statements between the FOR
and ENDFOR
lines are executed all over again, and this time x
is one bigger since it has been incremented.
In fact, this program does exactly the same as the following program (the `...' is not E code--it stands for the 97 other WriteF
statements):
PROC main() WriteF('\d ', 1) WriteF('\d ', 2) ... WriteF('\d ', 100) WriteF('\n') ENDPROC
The general form of the FOR
loop is as follows:
FOR var := expressionA TO expressionB STEP number statements ENDFOR
The var bit stands for the loop variable (in the example above this was x
).
The expressionA bit gives the start value for the loop variable and the expressionB bit gives the last allowable value for it.
The STEP
part allows you to specify the value (given by number) which is added to the loop variable on each loop.
Unlike the values given for the start and end (which can be arbitrary expressions), the STEP
value must be a constant (see 8 Constants).
The STEP
value defaults to one if the STEP
part is omitted (as in our example).
Negative STEP
values are allowed, but in this case the check used at the end of each loop is whether the loop variable is less than the value in the TO
part.
Zero is not allowed as the STEP
value.
As with the IF
block there is a horizontal form of a FOR
loop:
FOR var := expA TO expB STEP expC DO statement
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.