A loop ends only when its condition changes in the right way. To repair one, trace the variable in the condition and ask whether it can ever make the loop stop at the intended point.
This lesson is part of pseudocode for the applicable syllabus. It uses the tracing skill from assignment and comparison and the loop forms covered in repetition and arrays.
What are the usual termination bugs?
There are four. First, the condition variable is never updated. Second, the update moves it the wrong way.
Third, the test uses <> or = and the value jumps over it. Fourth, the test is off by one, using < where <= is needed.
For each bug, the fix is the same: decide what the loop should do, then make the update and the test agree.
Worked example
This loop should add 1, 3, 5, 7 and 9, and then stop.
Total ← 0
Count ← 1
WHILE Count <> 10 DO
Total ← Total + Count
Count ← Count + 2
ENDWHILE
OUTPUT Total
Trace the first rounds:
| Round | Count at test | Count <> 10 | Total after body | Count after body |
|---|---|---|---|---|
| 1 | 1 | TRUE | 1 | 3 |
| 2 | 3 | TRUE | 4 | 5 |
| 3 | 5 | TRUE | 9 | 7 |
| 4 | 7 | TRUE | 16 | 9 |
| 5 | 9 | TRUE | 25 | 11 |
| 6 | 11 | TRUE | 36 | 13 |
Count takes only odd values, so it jumps over 10 and the test is TRUE forever. The loop never terminates.
Repair: change the test to WHILE Count < 10 DO. Now round 5 ends with Count = 11, the test 11 < 10 is FALSE, and the loop stops. Total is 25. Check: 1 + 3 + 5 + 7 + 9 = 25.
The mistake to watch for
A common slip is fixing the symptom, not the cause.
Mistaken repair: change
Count + 2toCount + 1so that Count reaches 10.The loop now stops, but it adds 1 + 2 + 3 + … + 9 = 45. The algorithm no longer does what it was meant to do.
The correction is to keep the intended behaviour and change the test. Use < or <= rather than <> when a variable steps by more than 1, because a “not equal” test is only safe if the value will certainly land on the target.
Check yourself
1. X ← 20, WHILE X > 0 DO, X ← X - 6, ENDWHILE. What is X at the end, and how many times does the loop run?
Show answer
X goes 20, 14, 8, 2, then -4. The loop body runs 4 times and X ends at -4.
2. Why does Flag ← TRUE, WHILE Flag = TRUE DO OUTPUT "Hi" ENDWHILE never end?
Show answer
Nothing inside the loop changes Flag, so the condition stays TRUE. Add an update such as Flag ← FALSE under the right condition.
3. Start with Count ← 1, then REPEAT Count ← Count + 1 UNTIL Count > 5. What is Count at the end?
Show answer
Count goes 2, 3, 4, 5, 6. It stops when Count is 6, so Count is 6.
Where this leads next
Finish the module with checking the exam year before choosing notation. The restricted pseudocode trace trainer stops runaway loops at a safety limit, so you can test a faulty loop without freezing anything.
Debugging is a skill that grows from seeing your own mistakes explained. That is something our teachers do in online one-to-one Computer Science tuition.