A trace table (also called a dry run or desk check) is a manual method of testing an algorithm by stepping through it line by line and recording the value of each variable at every step.
You create columns for each variable, and one or more columns for any output. For each step of the algorithm, you fill in the current value of every variable that changes.
Follow these steps:
count ← 0
total ← 0
FOR i ← 1 TO 5
total ← total + i
count ← count + 1
NEXT i
OUTPUT total
OUTPUT count
Trace table:
| i | total | count | OUTPUT |
|---|---|---|---|
| — | 0 | 0 | |
| 1 | 1 | 1 | |
| 2 | 3 | 2 | |
| 3 | 6 | 3 | |
| 4 | 10 | 4 | |
| 5 | 15 | 5 | |
| 15 | |||
| 5 |
x ← 10
y ← 1
WHILE x > 0 DO
y ← y * 2
x ← x - 3
ENDWHILE
OUTPUT y
Trace table:
| x | y | OUTPUT |
|---|---|---|
| 10 | 1 | |
| 7 | 2 | |
| 4 | 4 | |
| 1 | 8 | |
| -2 | 16 | |
| (x = -2, condition x > 0 is FALSE, loop ends) | 16 | |
A trace table helps find three types of errors:
| Error Type | Description | Example |
|---|---|---|
| Logic error | Algorithm runs but gives wrong result | Using < instead of <=, causing loop to miss the last value |
| Infinite loop | Loop condition never becomes false | WHILE count < 10 but count is never incremented |
| Off-by-one error | Loop runs one too many or too few times | FOR i ← 1 TO 9 when you need 1 TO 10 |
4 questions · 10 marks
| Term | Definition |
|---|
10 minutes · mixed marks