An off-by-one error makes a loop run one time too many or one time too few. A trace table catches it because it forces you to write down every pass, including the one that never happened.
This lesson belongs to algorithm reasoning and test design. If tracing itself is new, read tracing pseudocode step by step first.
What should the algorithm do?
The task is to add the whole numbers from 1 to n. For n = 5 the answer should be 1 + 2 + 3 + 4 + 5 = 15.
A student wrote this:
INPUT n
SET total = 0
SET i = 1
WHILE i < n
SET total = total + i
SET i = i + 1
END WHILE
OUTPUT total
How do you trace it?
Make one column for each variable and one for the loop condition. Add a row each time the condition is checked, not only when the body runs.
| Check | i | i < n | total after body |
|---|---|---|---|
| 1 | 1 | 1 < 5 TRUE | 1 |
| 2 | 2 | 2 < 5 TRUE | 3 |
| 3 | 3 | 3 < 5 TRUE | 6 |
| 4 | 4 | 4 < 5 TRUE | 10 |
| 5 | 5 | 5 < 5 FALSE | (stops) |
The output is 10, not 15. The last row explains why: when i reaches 5 the condition 5 < 5 is false, so the number 5 is never added.
What is the fix, and how do you confirm it?
Change the condition to i <= n. Trace again and the fifth check becomes 5 <= 5 TRUE, which adds 5 to give total = 15.
There is now a sixth check, 6 <= 5 FALSE, and the loop stops. Always run the corrected version through the same table, because a fix can move the error instead of removing it.
The mistake to avoid
A common slip is to trace only the passes that run and forget the failed check. The table looks complete, but the missing pass stays hidden.
| Habit | What it hides |
|---|---|
| Writing rows only for body passes | The pass the loop refused |
| Jumping to the final total | Which row went wrong |
| Adding the failed check as a last row | Nothing: the stop is visible |
A quick test is to count rows. If the task needs five additions and your table shows four, the loop is one short.
Check yourself
This algorithm should add the squares of 1, 2, 3 and 4.
SET total = 0
FOR i = 2 TO 4
SET total = total + i * i
NEXT i
OUTPUT total
What does it output, and what should it output?
Answer
The loop runs for i = 2, 3 and 4. The total grows as 4, then 13, then 29, so it outputs 29.
The task needs 1² + 2² + 3² + 4² = 1 + 4 + 9 + 16 = 30. The loop starts at 2, so the pass for i = 1 is missing. Change the start to FOR i = 1 TO 4.
What to study next
Next, learn to pick inputs that make these errors show up: choosing normal, boundary and invalid test data. You can also practise on your own device with the restricted pseudocode trace trainer.
If you want a teacher to trace your own loops with you, see online one-to-one Computer Science tuition.