Computers are brilliant at one thing above all: doing the same job over and over without getting bored. Iteration — looping — is how you tell a program to repeat a block of code. Instead of writing "print star" fifty times, you write it once and say "do that fifty times". Loops turn long, repetitive tasks into a few tidy lines.
Count-controlled loops (FOR)
When you know exactly how many times to repeat, use a FOR loop. A counter variable steps through a range of numbers automatically.
FOR i ← 1 TO 5
OUTPUT i
NEXT i
This outputs 1, 2, 3, 4, 5. Picture a runner doing five laps of a track: the loop counts each lap for you and stops on its own. This is the loop to reach for when the number of repeats is fixed.
Condition-controlled loops (WHILE)
Sometimes you do not know how many repeats you need — you keep going until something happens. A WHILE loop checks a condition before each pass and stops as soon as it becomes False.
total = 0
WHILE total < 10
total = total + 3
ENDWHILE
Like eating chips until you are full: you cannot say in advance how many, you just keep checking.
REPEAT UNTIL: check at the end
A REPEAT ... UNTIL loop tests its condition after the body, so the body always runs at least once. Handy for asking a user to try again.
| Loop | Use when | Test happens |
|---|---|---|
| FOR | Repeats are counted / fixed | — |
| WHILE | Repeats unknown, may be zero | Before the body |
| REPEAT UNTIL | Repeats unknown, at least one | After the body |
Start:
total = 0. Is 0 < 10? Yes → total = 3.Is 3 < 10? Yes → total = 6.
Is 6 < 10? Yes → total = 9.
Is 9 < 10? Yes → total = 12.
Is 12 < 10? No → stop. Final total = 12 (the loop ran 4 times).
total inside the loop — the program repeats forever. Always make sure something inside the loop moves you towards the exit.Ask yourself one question to pick the loop: "Do I know the number of repeats?" Yes → FOR. No → WHILE (or REPEAT UNTIL if it must run at least once).