Sub topic 7
Building a Trace Table
This chapter assumes you can already read the pseudocode conventions from earlier chapters: ← for assignment, IF … THEN … ELSE, counted FOR loops, and functions that RETURN a value. It also assumes basic programming in any language. The aim is a method for recording exactly what an algorithm does, so you check the steps on paper instead of running them in your head and hoping you got them right.
What a Trace Table Is
A trace table is a grid that records the state of an algorithm as it runs. Each column holds one variable, condition, or output. Each row holds one step. Reading down a column shows how a single variable changes over time. Reading across a row shows the whole program state at one moment.
The table replaces your working memory. Most hand-tracing mistakes come from remembering a value wrongly, such as using an old value of x after it changed. With a table you look up the value instead of recalling it.
Anatomy of a Trace Table
| Column type | What it holds | Example header |
|---|---|---|
| Step or line | Which statement or iteration this row covers | `step`, `line` |
| Variable | The value after the step runs | `i`, `max`, `total` |
| Condition | The result of a test evaluated in this step | `A[i] > max` |
| Output | Anything printed or returned | `output`, `returns` |
Condition columns are optional, but you should include them. A wrong branch is one of the most common logic errors, and a condition column puts the true/false result where you can see it.
The Procedure
- Write down the inputs and the expected answer before you start. If you don't decide the expected result first, you will tend to accept whatever result the trace gives you.
- Make one column for every variable the algorithm assigns, plus columns for conditions and output.
- Fill in the first row with the inputs and initial values. Mark any variable that has not been assigned yet with
-or?. - Execute one statement at a time, as written, not as intended.
- When a value changes, write it in a new row. Leave unchanged cells blank, or copy the old value forward. Pick one convention and keep it for the whole table.
- At the end, compare the returned or printed value with your expected answer.
Worked Example: Sequence
Sequence is the simplest case, because every statement runs once and in order. Here is a swap of two variables:
a ← 5
b ← 8
temp ← a
a ← b
b ← tempExpected result: a = 8, b = 5.
line | a | b | temp
-----+---+---+-----
1 | 5 | ? | ?
2 | 5 | 8 | ?
3 | 5 | 8 | 5
4 | 8 | 8 | 5
5 | 8 | 5 | 5The trace matches the expected result. Now trace the common incorrect version, which leaves out temp:
a ← 5
b ← 8
a ← b
b ← aline | a | b
-----+---+---
1 | 5 | ?
2 | 5 | 8
3 | 8 | 8
4 | 8 | 8Row 3 shows the bug. Once a is overwritten, its original value is gone. Line 4 reads the current value of a, which is 8. People who trace in their head often treat line 4 as "b gets the old a" because that is what the code was meant to do. The table forces you to read the latest row.
Worked Example: Selection
With branches, the table also has to show which path ran. Add a condition column, and record only the conditions that were actually evaluated.
FUNCTION Shipping(weight, member)
IF member THEN
cost ← 0
ELSE IF weight ≤ 2 THEN
cost ← 5
ELSE
cost ← 5 + 2 × (weight - 2)
END IF
RETURN cost
END FUNCTIONInput: weight = 4, member = false. Expected: 5 for the first 2 kg plus 2 × 2 for the rest, which gives 9.
step | weight | member | condition | result | cost | returns
-----+--------+--------+-----------------+--------+------+--------
init | 4 | false | - | - | ? | -
1 | 4 | false | member | false | ? | -
2 | 4 | false | weight ≤ 2 | false | ? | -
3 | 4 | false | - | - | 9 | -
4 | 4 | false | - | - | 9 | 9There is no row for cost ← 0 or cost ← 5, because those statements never ran. A branch that was skipped gets no row. If your table shows a value assigned on a path whose condition was false, you have made a trace error.
A single trace covers only one path. This function has three paths, so it needs at least three traces to cover it: one with member = true, one with a weight of 2 or less, and one with a weight above 2. The chapter on picking inputs looks at this in more detail.
A Preview: Tables with Loops
Loops add rows that repeat, and the loop variable gets a column of its own. Here is FindMax traced on A = [3, 7, 2, 9]:
FUNCTION FindMax(A, n)
max ← A[1]
FOR i ← 2 TO n DO
IF A[i] > max THEN
max ← A[i]
END IF
END FOR
RETURN max
END FUNCTIONstep | i | A[i] | A[i] > max | max
-----+---+------+------------+----
init | - | - | - | 3
1 | 2 | 7 | true | 7
2 | 3 | 2 | false | 7
3 | 4 | 9 | true | 9
Returns 9This table uses one row per iteration instead of one row per line. The condition is evaluated against the value of max before the iteration's update, and the max column shows the value after it. The next chapter covers loop tracing in detail, including how to show termination.
Choosing Row Granularity
| Granularity | Use when | Risk |
|---|---|---|
| One row per line | Short sequences, finding a specific bug | Tables get long quickly |
| One row per iteration | Loops whose bodies are well understood | Hides the order of updates inside the body |
| One row per call | Procedure calls and recursion | Hides the internal steps of each call |
If you suspect a bug inside a loop body, switch to one row per line for the iterations you suspect.
Common Errors
- Reading from memory instead of the table. Every value you use must come from the most recent row in which that variable was written.
- Updating at the same time. Statements run one after another.
a ← bfollowed byb ← adoes not swap, because the second line sees the newa. - Tracing intent, not text. If the code says
<, evaluate<, even when you are sure the author meant≤. - Inventing initial values. An unassigned variable is
?. If the algorithm reads a?, you have found a real bug. - Mixing conventions. Use either blank-means-unchanged or copy-forward. Switching halfway through a table causes misreads.
- Skipping the expected answer. If you don't set the expected answer first, the trace has nothing to be checked against.
Checking a Hand Trace with Code
When you can run code, printing the state at each step gives a machine-made trace table you can compare with yours. This Python version of Shipping prints one row for each evaluated condition and each assignment:
def shipping(weight, member):
print(f"{'condition':<12} | {'result':<6} | cost")
cost = None
print(f"{'member':<12} | {str(member):<6} | {cost}")
if member:
cost = 0
else:
test = weight <= 2
print(f"{'weight <= 2':<12} | {str(test):<6} | {cost}")
if test:
cost = 5
else:
cost = 5 + 2 * (weight - 2)
print(f"{'-':<12} | {'-':<6} | {cost}")
return cost
print("returns", shipping(4, False))The output shows member is False, then weight <= 2 is False, then cost is 9, and the function returns 9. That matches the hand trace row for row. Use this check to confirm your paper method, not to replace it. The value of hand tracing is that you can do it before any code exists.
Exercise
Build a trace table for this pseudocode and give the final values of x and y: x ← 3; y ← x + 2; x ← x × y; y ← x - y. Use one row per line and copy unchanged values forward.
Show answer
Line 1: x = 3, y = ?. Line 2: x = 3, y = 5. Line 3: x = 15, y = 5. Line 4: x = 15, y = 10. Final values: x = 15, y = 10. Line 4 uses the new x (15), not the original 3.
Exercise
Trace Shipping(2, false). Which condition rows appear, which assignment runs, and what is returned? Then name an input that makes the trace contain only one condition row.
Show answer
The condition member evaluates to false, then weight ≤ 2 evaluates to true (2 ≤ 2), so cost ← 5 runs and the function returns 5. The ELSE branch gets no row. Any input with member = true, such as Shipping(10, true), evaluates only the member condition and returns 0.
Exercise
A student traces the two-line swap a ← b; b ← a with a = 5, b = 8 and writes a final row of a = 8, b = 5. What tracing error did they make, and how does the table expose it?
Show answer
They traced the intent instead of the text, using the old value of a on line 2. In a correct table, the row for line 1 already shows a = 8, so line 2 must read 8 and gives b = 8. Reading each value from the latest row prevents this error.