Trace Tables
1. What is a Trace Table?
A Trace Table is a tool used to track the values of variables as an algorithm executes line by line. Its primary purpose is to find Logic Errors that a compiler might miss.
2. Example: Totaling & Counting
Let's trace this pseudocode algorithm which finds the total and count of 3 numbers entered by a user.
Total ← 0
Count ← 0
WHILE Count < 3 DO
INPUT Num
Total ← Total + Num
Count ← Count + 1
ENDWHILE
OUTPUT Total
Count ← 0
WHILE Count < 3 DO
INPUT Num
Total ← Total + Num
Count ← Count + 1
ENDWHILE
OUTPUT Total
Trace Table (Test Data: 10, 5, 20)
| Total | Count | Num | OUTPUT |
|---|---|---|---|
| 0 | 0 | ||
| 10 | |||
| 10 | 1 | ||
| 5 | |||
| 15 | 2 | ||
| 20 | |||
| 35 | 3 | ||
| 35 |
3. Rules for Drawing Trace Tables
- Each row represents a change in a variable's value or an input.
- Do not repeat values in a row if they haven't changed (leave the cell blank or use a dash).
- Output only goes in the output column when the program explicitly executes an
OUTPUTorPRINTcommand. - Calculations (like
Total + Num) are performed first, then the new value is written in the table.
4. Why use Trace Tables?
- To verify that an algorithm works correctly with Test Data.
- To identify Infinite Loops (where a variable never meets the exit condition).
- To find "Off-by-one" errors (e.g., using
Count < 3vsCount <= 3).
⚠️ Exam Warning: When filling out a trace table in an exam, be very careful with Loops. The most common mistake is forgetting to increment the counter or stopping one iteration too early.