Trace Tables
A trace table is a technique for tracking the values of variables as a program executes, line by line. It is the most reliable way to verify an algorithm works correctly — or to find bugs.
Learning Objectives
- 11.5.1.4 Use trace tables to verify algorithms and predict outputs
Conceptual Anchor
The Detective Analogy
A trace table is like a detective's evidence log. For every step the suspect (program) takes, you record what changed. At the end, you can see the full journey and verify if the outcome matches expectations — or find where things went wrong.
Rules & Theory
How to Build a Trace Table
| Step | Action |
|---|---|
| 1 | Create a column for each variable + one for output |
| 2 | Add a row for each line that changes a variable |
| 3 | Execute each line mentally, recording new values |
| 4 | Leave cells empty if a variable doesn't change |
| 5 | For loops, add a new row for each iteration |
Worked Examples
1 Trace: Find the Sum of 1 to 5
// Pseudocode:
sum ← 0
FOR i ← 1 TO 5
sum ← sum + i
ENDFOR
OUTPUT sum
Trace Table:
Step │ i │ sum │ Output
──────┼─────┼─────┼────────
1 │ — │ 0 │ —
2 │ 1 │ 1 │ —
3 │ 2 │ 3 │ —
4 │ 3 │ 6 │ —
5 │ 4 │ 10 │ —
6 │ 5 │ 15 │ —
7 │ — │ — │ 152 Trace: Swap Two Variables
// Pseudocode:
a ← 7
b ← 3
temp ← a
a ← b
b ← temp
OUTPUT a, b
Trace Table:
Step │ a │ b │ temp │ Output
──────┼─────┼─────┼──────┼────────
1 │ 7 │ — │ — │ —
2 │ 7 │ 3 │ — │ —
3 │ 7 │ 3 │ 7 │ —
4 │ 3 │ 3 │ 7 │ —
5 │ 3 │ 7 │ 7 │ —
6 │ — │ — │ — │ 3, 73 Trace: Find Maximum in Array [4, 9, 2, 7]
// Pseudocode:
arr ← [4, 9, 2, 7]
max ← arr[0]
FOR i ← 1 TO 3
IF arr[i] > max THEN
max ← arr[i]
ENDIF
ENDFOR
OUTPUT max
Trace Table:
Step │ i │ arr[i] │ max │ Output
──────┼─────┼────────┼─────┼────────
1 │ — │ — │ 4 │ —
2 │ 1 │ 9 │ 9 │ — (9>4 ✓)
3 │ 2 │ 2 │ 9 │ — (2>9 ✗)
4 │ 3 │ 7 │ 9 │ — (7>9 ✗)
5 │ — │ — │ — │ 9Common Pitfalls
Skipping Iterations
Every loop iteration needs its own row — even if no variable changes. If an IF condition is false, you still need to show that the step was checked.
Overwriting Old Values
Each row shows the new value of a variable. The old value is in the previous row. Never erase previous rows — the history is the whole point!
Tasks
Create a trace table for: x ← 10, WHILE x > 0: OUTPUT x, x ← x - 3.
Trace the following and find the output: a ← 1, FOR i ← 1 TO 4: a ← a * 2.
A student claims this code finds the minimum of an array. Use a trace table with [5, 2, 8, 1] to verify or disprove their claim.
Self-Check Quiz
Q1: What is the purpose of a trace table?
Q2: What should each column represent?
Q3: How many rows does a loop with 5 iterations need?