For |
Loops | |
Aptilis 1 |
For
for var = startvalue to lastvalue
line of code
line of code
end for
OR:
for var = startvalue to lastvalue step increment
line of code
line of code
end for
For allows you to repeat a block of lines for a given number of times.
The for line is evaluated the first time it is entcountered so
the block of lines might not be run if the condition is not true.
Example: for i=2 to 1
The startvalue and
lastvalue are computed once and for all at the begining
of the loop. Those values may be expressions with variables.
Even if those variables are altered within the loop, that will
not change the behaviour of the loop which has been defined
by the for line.
For uses your control variable var and increments it by one,
at the end of the for loop. An optional level
of control is possible: instead of incrementing by one,
the step statement allows you to choose the
increment. (See example 2)
Two other statements can be used in all loops:
- break; to exit from a loop (example 3)
- continue; to interrupt the current iteration and
start over from the begining of the loop, after having
carried out the incrementation. (example 4)
Loops of any kind can be nested, but not intertwined.
Correct:
for i=1 to 5 repeat .. .. until a = "" $ end for
Incorrect:
for i=1 to 5 repeat .. .. end for until a = "" $
Example 1:
(Don't forget the space between end and for!)
// Table of 4 for i=1 to 4 print(int(i)$, " * 4=", i * 4, "\n") end forResult:
1 * 4=4.0000 2 * 4=8.0000 3 * 4=12.0000 4 * 4=16.0000 |
Example 2:
for j=3 to 1 step -1 print(j, "\n") end forResult:
3 2 1 |
Example 3:
for k=1 to 10 print(k, "\n") if k = 3 break end if end forResult:
1 2 3 |
Example 4:
for l=1 to 4 if l = 2 continue end if print(l, "\n") end forResult:
1 3 4 |
Notes:
The test is carried out from the first iteration, the
incrementation (or decrementation) is done at the end
of each iteration.