Sub topic 7
Building a Trace Table
This chapter assumes you can read the pseudocode conventions covered earlier: ← for assignment, IF ... THEN ... END IF blocks, and indentation that shows structure. It also assumes you know what a variable is and how a conditional runs in at least one programming language.
A trace table is a grid that records the value of each variable as an algorithm runs, one step at a time. It replaces "I think this works" with a written record you can check line by line. Building one is a mechanical skill, and the mechanics matter more than speed.
Anatomy of a Trace Table
A trace table has three kinds of columns:
| Column type | Purpose | Example |
|---|---|---|
| Step or line | Identifies which statement just ran | `3` |
| Variables | One column per variable, showing its value after the step | `a`, `b`, `temp` |
| Conditions or output | The result of any test or printed value | `a > b` = true |
Each row is one executed statement. A cell is filled only when that variable changes. A blank cell means "unchanged since the last value above it," and you won't confuse it with zero.
A Worked Example
Here is a short algorithm with a sequence and a selection, numbered so each line can be referenced:
1 a ← 5
2 b ← 3
3 IF a > b THEN
4 temp ← a
5 a ← b
6 b ← temp
7 END IF
8 c ← a + 2 × bTrace it by executing exactly one line per row and writing only what that line changes:
line | a | b | temp | a > b | c
-----+---+---+------+-------+----
1 | 5 | | | |
2 | | 3 | | |
3 | | | | true |
4 | | | 5 | |
5 | 3 | | | |
6 | | 5 | | |
8 | | | | | 13Line 7 has no row because END IF does nothing at runtime. On line 8, the current values are a = 3 and b = 5, so c = 3 + 2 × 5 = 13. To find a variable's current value, read up its column to the most recent filled cell.
The Procedure
Common Errors
- Updating from memory instead of the table. If you "know"
ais 5, you will miss the swap on line 5. Always read the column. - Evaluating a whole block at once. Collapsing lines 4 to 6 into "swap them" hides the order of the steps. If line 5 and line 6 were reversed, the swap would break, and only a line-by-line trace shows it.
- Skipping the condition column. If you don't record the test result, nothing on paper shows which branch you took, and branch errors stay hidden.
- Writing every variable on every row. Copying unchanged values adds clutter and room for copying mistakes. Fill only the cells that change.
The next chapter applies this same table to loops, where one line runs many times and the step column becomes essential.
Exercise
Trace the worked example again, but change line 1 to a ← 2 and line 2 to b ← 8. Which rows appear in your table, what is the final value of c, and what value does temp hold at the end?
Show answer
The rows are lines 1 (a = 2), 2 (b = 8), 3 (a > b is false), and 8 (c = 2 + 2 × 8 = 18). Lines 4 to 6 never run, so temp is never assigned. Its column stays empty, which means it has no value, not zero. Final c = 18.