A loop that misbehaves usually fails one of three checks: the starting value, the condition, or the update. Tracing the condition on every pass shows which one is at fault.
This lesson is part of program structure and debugging. The basic limits of loops are covered in writing loops with correct boundaries.
Example 1: a loop that never ends
The program should count down to zero in steps of 3, printing each value.
SET n = 10
WHILE n <> 0
OUTPUT n
SET n = n - 3
END WHILE
| Pass | n before | n <> 0 | n after |
|---|---|---|---|
| 1 | 10 | TRUE | 7 |
| 2 | 7 | TRUE | 4 |
| 3 | 4 | TRUE | 1 |
| 4 | 1 | TRUE | −2 |
| 5 | −2 | TRUE | −5 |
The values are 10, 7, 4, 1, −2 and so on. The value 0 is never reached, because the step of 3 jumps over it, so n <> 0 is always true. The loop never ends.
The fix is to change the condition to n > 0. Now the loop prints 10, 7, 4, 1 and stops when n becomes −2.
Example 2: a loop that stops too early
The program should add five marks, then output the total.
SET total = 0
INPUT mark
WHILE mark > 0
SET total = total + mark
INPUT mark
END WHILE
OUTPUT total
The marks are 70, 0, 55, 80 and 90. A student scored 0 in the second paper, and that is a real mark.
| Step | mark | mark > 0 | total |
|---|---|---|---|
| Read first | 70 | TRUE | 70 |
| Read second | 0 | FALSE | 70 |
The loop ends and outputs 70, but the correct total is 70 + 0 + 55 + 80 + 90 = 295. The stop condition treats a valid 0 as an end signal.
The fix is to count the marks instead. Use FOR i = 1 TO 5, which always reads exactly five values.
How do you diagnose any loop?
Run three checks in order.
- Start: does the variable begin at the right value?
- Condition: can it ever become false, and could it become false too soon on valid data?
- Update: does the body move the variable toward the stop?
A mistake to avoid is fixing the first symptom you notice. Always trace at least three passes before changing anything.
Check yourself
Why does this loop never end, and how do you fix it?
SET x = 1
WHILE x <> 10
SET x = x + 2
END WHILE
Answer
The values of x are 1, 3, 5, 7, 9, 11 and onward, all odd, so x never equals 10. The condition x <> 10 stays true forever.
Change it to WHILE x < 10. The loop then stops when x reaches 11.
What to study next
Next, learn to tell a typing fault from a design fault in distinguishing a syntax error from a logically wrong result. The restricted pseudocode trace trainer offers more loop traces.
If you want a teacher to go through your own loops, see online one-to-one Computer Science tuition.