A trace table records the value of each variable after each step. It lets you find logic errors without a computer.
Trace of the Sum of 1 to N algorithm with N = 4:
| Step | i | total | Condition i <= 4 |
|---|---|---|---|
| Start | 1 | 0 | true |
| After pass 1 | 2 | 1 | true |
| After pass 2 | 3 | 3 | true |
| After pass 3 | 4 | 6 | true |
| After pass 4 | 5 | 10 | false, loop ends |
The output is 10, which is correct (1 + 2 + 3 + 4).
Why trace?
When you read an algorithm, your brain fills in what you meant to write. A trace table makes you follow what is actually written, one step at a time, just as the computer will. Errors that you would never spot by reading become obvious when a value in the table is not the one you expected.
How to build a trace table
- Make one column for each variable, one for each condition that is tested, and one for output.
- Fill in the first row with the starting values (after the variables are first set).
- Follow the algorithm one step at a time. Each time a variable changes, write its new value in a new row. Never skip a step "because it is obvious".
- When a condition is tested, write true or false; this tells you which way the program goes.
- When the algorithm ends, compare the output with the answer you worked out by hand.
Finding a logic error with a trace
Suppose the loop condition was written as i < N instead of i <= N. Trace it with N = 4:
| Step | i | total | Condition i < 4 |
|---|---|---|---|
| Start | 1 | 0 | true |
| After pass 1 | 2 | 1 | true |
| After pass 2 | 3 | 3 | true |
| After pass 3 | 4 | 6 | false, loop ends |
The output is 6, but the correct answer is 10. The table shows exactly what went wrong: the loop stopped when i was 4, so 4 was never added. A single wrong character, < instead of <=, caused it. This is called an off-by-one error, and it is one of the most common logic errors in programming.
A trace with a decision
Algorithm: read three numbers and find the largest.
READ a, b, c
largest = a
IF b > largest THEN largest = b
IF c > largest THEN largest = c
PRINT largestTrace with a = 4, b = 9, c = 7:
| Step | a | b | c | largest | Condition |
|---|---|---|---|---|---|
| After READ | 4 | 9 | 7 | ||
| largest = a | 4 | 9 | 7 | 4 | |
| IF b > largest | 9 | 9 > 4 is true | |||
| IF c > largest | 9 | 7 > 9 is false | |||
| 9 | Output: 9 |
Now try (5, 5, 2) yourself: the answer should be 5. Equal values are a good test, because they check whether > or >= was the right choice.
Tip: use small, simple test values when you trace. You want to check the logic, not your arithmetic.
Use the stepper below to watch a trace table being filled in, one pass at a time.