Repetition — the FOR Loop
Repetition executes a block of statements more than once. The FOR loop is the variant used when you know in advance how many times to repeat.
The form
FOR counter ← start TO end
statements
ENDFOR
The counter is initialised to start, the body runs, the counter increases by
one, and this continues while the counter has not passed end.
FOR i ← 1 TO 5
PRINT i
ENDFOR
prints 1, 2, 3, 4, 5. Five iterations.
Counting downward
Add STEP -1:
FOR i ← 50 DOWNTO 1
PRINT i
ENDFOR
or equivalently
FOR i ← 50 TO 1 STEP -1
Both are accepted conventions. Be consistent within one answer.
Counting how many iterations
For FOR i ← a TO b the body runs times.
FOR i ← 1 TO 5 → ✓
FOR i ← 0 TO 4 → ✓
FOR i ← 3 TO 3 → — runs once, not zero
FOR i ← 5 TO 1 → → runs zero times
The +1 catches people out. Off-by-one errors are the commonest loop bug, and
this formula is how you check.
When to use FOR
Use FOR when the iteration count is known before the loop starts:
- Repeat exactly n times
- Process every element of a list of known length
- Count 1 to 50
Do not use FOR when the loop should stop on a condition discovered during execution — reading until the user types 0, or until a value is found. That's a WHILE loop.
Don't modify the counter inside the loop
FOR i ← 1 TO 10
i ← i + 2 ← wrong
ENDFOR
The FOR loop manages its own counter. Changing it inside makes the iteration count unpredictable and is a defect in almost every case. If you need irregular stepping, use WHILE.
Accumulator pattern
The most common use of a counted loop: build up a total.
sum ← 0 initialise BEFORE the loop
FOR i ← 1 TO n
READ x
sum ← sum + x
ENDFOR
PRINT sum
Two rules: initialise the accumulator before the loop (0 for sums, 1 for products), and update it inside. Initialising inside resets it every iteration — a classic error that leaves you with only the last value.