While |
Loops | |
Aptilis 1 |
While
while expr
line of code
line of code
end while
while allows you to repeat a block of lines
as long as a condition is true.
As the test is carried out from the start,
a while block might never be run.
Two other statements can be used in all loops:
- break; to exit from a loop (example 2)
- continue; to interrupt the current iteration and
start over from the begining of the loop. (example 3)
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:
(A classic mistake is to forget to increment the
control variable, something that is done automatically
by the for loop)
// Table of 4 i = 1 while i < 5 print(int(i), "* 4 = ", i * 4,"\n") i = i + 1 end whileResult:
1 * 4 = 4.0000 2 * 4 = 8.0000 3 * 4 = 12.0000 4 * 4 = 16.0000 |
Example 2:
k = 1 while k < 10 print(k, "\n") if k = 3 break end if k = k + 1 end whileResult:
1 2 3 |
Example 3:
l = 0 while l < 5 l = l + 1 if l = 2 continue end if print(l, "\n") end whileResult:
1 3 4 5 |