When a trace surprises you, the cause is a skipped check of the loop condition. A table that gives the condition its own column removes that shortcut.
This page is for the moment when your answer and the printed output disagree and you need to know why.
How do you lay out the trace table?
Give the table a column for the pass number, one for the condition, and one for each variable. Add a start row before the loop, then one row for each pass.
Write the condition result before you run the body. That habit is the whole method.
A worked example that surprises
n ← 10
count ← 0
WHILE n > 0
n ← n - 3
count ← count + 1
END WHILE
OUTPUT count, n
Students expect “3 and 1”, because n goes 10, 7, 4, 1 and it looks as if the loop should stop there. Trace it properly.
| Pass | n > 0 at top | n after body | count after body |
|---|---|---|---|
| start | 10 | 0 | |
| 1 | true (10) | 7 | 1 |
| 2 | true (7) | 4 | 2 |
| 3 | true (4) | 1 | 3 |
| 4 | true (1) | −2 | 4 |
| test | false (−2) |
The value 1 is still above 0, so the body runs a fourth time. The output is 4 and −2.
The surprise comes from the condition test. It happens at the top of each pass, so n can end below the boundary.
How do you find which step you got wrong?
Compare your own table with the trace above and look for the first row that differs. The difference is likely to be one of these.
- You stopped when n reached a value near 0, not when n > 0 became false.
- You changed n and count in the wrong order.
- You forgot that the body finishes the pass after the condition was true.
The trace pseudocode lesson explains the row-by-row method, and the loop diagnosis lesson covers loops that stop early or never stop.
A self-check
Trace this loop and give the output.
x ← 2
total ← 0
WHILE x < 20
x ← x * 3
total ← total + x
END WHILE
OUTPUT total
Answer
x starts at 2. Pass 1: 2 < 20 is true, x becomes 6, total becomes 6.
Pass 2: 6 < 20 is true, x becomes 18, total becomes 24.
Pass 3: 18 < 20 is true, x becomes 54, total becomes 78. Then 54 < 20 is false.
The output is 78.
How can you practise?
Use the restricted pseudocode trace trainer with short loops, and record each wrong trace in the mistake log. The log shows which row type you miss.
When is one-to-one tuition worth considering?
If you trace carefully and still get a different answer, a teacher can trace alongside you and stop at the row where your path splits from the program’s. That can take minutes, where searching alone can take much longer.
You can try it in the one-hour trial class (from RM50), a taught lesson. See also online one-to-one Computer Science tuition.