Tracing means acting as the computer: follow each line in order, and record every variable after every change. The table becomes your evidence for what the algorithm does.
This lesson is part of problem solving and algorithms. It follows on from breaking a problem into smaller tasks.
What are the rules of a good trace?
Keep to four habits.
- One column per variable, plus one for any output.
- Write the starting values in the first row.
- Change only the cell that the current line changes.
- Copy other values down unchanged, so a row is always a complete snapshot.
Worked example: adding the digits of a number
The pseudocode adds the digits of n, where n = 482.
INPUT n
SET sum = 0
WHILE n > 0
SET digit = n MOD 10
SET sum = sum + digit
SET n = n DIV 10
END WHILE
OUTPUT sum
| Step | n | digit | sum | n > 0 |
|---|---|---|---|---|
| Start | 482 | 0 | TRUE | |
| Pass 1 | 48 | 2 | 2 | TRUE |
| Pass 2 | 4 | 8 | 10 | TRUE |
| Pass 3 | 0 | 4 | 14 | FALSE |
The loop stops and outputs 14. Check: 4 + 8 + 2 = 14, which matches.
What mistake breaks the trace?
The usual error is to update n too early. Suppose a student writes the pass 1 row as n = 48 and then takes digit = 48 MOD 10 = 8, using the new n.
| Approach | digit in pass 1 | Final sum |
|---|---|---|
| Wrong: use n after it changes | 8 | 8 + 4 + 0 = 12 |
| Right: use n as it was before the line | 2 | 14 |
The fix is to read only the values in the previous row when you work out a new row. Never use a value that the current line is about to change.
How do you handle a loop condition?
Write the condition result as its own column, as above. Then the stopping point is on the page, and you can see whether the last pass happened.
If your final value looks strange, look first at the condition column. The usual cause is a loop that stopped one pass early or late, which is the subject of writing a trace table that exposes an off-by-one error.
Check yourself
Trace the same pseudocode for n = 305 and state the output.
Answer
Start: n = 305, sum = 0. Pass 1: digit = 5, sum = 5, n = 30. Pass 2: digit = 0, sum = 5, n = 3.
Pass 3: digit = 3, sum = 8, n = 0. The condition 0 > 0 is false.
The output is 8. Note that the middle digit 0 still gets a row; skipping it would lose the pass.
What to study next
Next, turn a sequence of steps into a diagram with designing a flowchart. You can also practise tracing with the restricted pseudocode trace trainer.
If you would like a teacher to check your traces as you write them, see online one-to-one Computer Science tuition.