Repetition — the WHILE Loop
A WHILE loop repeats as long as a condition remains true. Use it when the number of iterations is not known before the loop starts.
The form
WHILE condition DO
statements
ENDWHILE
The condition is tested before each iteration. If it is false at the very first test, the body never runs at all — a pre-test or entry-controlled loop.
i ← 1
WHILE i <= 5 DO
PRINT i
i ← i + 1
ENDWHILE
The three parts every WHILE needs
Miss any one and the loop misbehaves. Check all three, every time.
| Part | Where | Purpose |
|---|---|---|
| Initialisation | Before the loop | Give the control variable a starting value |
| Condition | In the WHILE | Decide whether to continue |
| Update | Inside the body | Move the variable towards making the condition false |
i ← 1 1. initialise
WHILE i <= 5 DO 2. condition
PRINT i
i ← i + 1 3. update ← the one people forget
ENDWHILE
Omit the update and i stays 1 forever. The condition never becomes false.
Infinite loop.
Causes of infinite loops
1. No update. As above.
2. Update in the wrong direction.
i ← 1
WHILE i <= 5 DO
i ← i - 1 moves away from the condition
ENDWHILE
3. A condition that can never be false.
WHILE x <> 5 DO if x is a float, exact equality may never hold
Prefer < or > over = and <> when the variable is a float, for exactly
the floating-point reasons met in Module 1.
4. The update is inside an IF that doesn't always run.
WHILE count < 10 DO
READ x
IF x > 0 THEN
count ← count + 1
ENDIF
ENDWHILE
If the user only ever enters negative numbers, count never advances.
Sometimes this is intended; usually it isn't. Ask yourself whether every path
through the body makes progress.
Sentinel-controlled loops
A sentinel is a special value marking the end of input.
BEGIN
sum ← 0
READ x
WHILE x <> 0 DO 0 is the sentinel
sum ← sum + x
READ x
ENDWHILE
PRINT "Sum is", sum
END
Note the structure: read once before the loop, then read again at the end of the body. This is the priming read, and it is what students most often get wrong.
Without the priming read, the first WHILE test examines an uninitialised
variable. With the read only at the top of the body, the sentinel itself gets
added to the sum before the condition is retested.
The sentinel must be a value that cannot occur as real data. Using 0 to end a list of marks is fine; using it to end a list of temperatures is not.