Trace tables explained
6 min readUpdated
A trace table records how the values of variables change as an algorithm runs, one line at a time. Exams use them to test whether you can read code, and they are also the fastest way to find a bug by hand.
How to set one up
- Make one column for every variable, one for any condition you need to check, and one for output.
- Add a new row each time a value changes.
- Only fill a cell when that value changes; leave the rest blank or copy the value, as your exam expects.
Worked example
total = 0
count = 1
while count <= 4:
total = total + count
count = count + 2
print(total)| count | total | count <= 4 | Output |
|---|---|---|---|
| 1 | 0 | True | |
| 3 | 1 | True | |
| 5 | 4 | False | |
| 4 |
The loop adds 1, then 3. When count becomes 5 the condition is false, the loop ends and 4 is printed.
Tracing a loop over a list
marks = [7, 3, 9, 4]
highest = marks[0]
for m in marks:
if m > highest:
highest = m
print(highest)| m | m > highest | highest | Output |
|---|---|---|---|
| 7 | |||
| 7 | False | 7 | |
| 3 | False | 7 | |
| 9 | True | 9 | |
| 4 | False | 9 | |
| 9 |
Tips that save marks
- Work one line at a time; never jump ahead because you think you know the answer.
- Check the loop condition every time round, including the last time when it is false.
- Watch integer division (
//) and remainder (%). - Write outputs in the order they happen.
Using trace tables to debug
When your program gives the wrong answer, trace it with a small input. The row where a value first goes wrong points to the faulty line. This works especially well for off-by-one errors and wrong conditions.
Frequently asked questions
Do I need to repeat values that did not change?
It depends on the mark scheme. Most accept either; a new row only when something changes is the clearest style.
What if there is a nested loop?
Give each loop variable its own column and trace the inner loop fully for each step of the outer loop.
Can trace tables be used for recursion?
Yes, but a call table showing each call and its return value is usually clearer.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.