A trace table is a technique used to manually track the value of variables and conditions at each step of an algorithm. It is used to check whether an algorithm produces the correct output and to find any errors.
Each column in the trace table represents one variable (or output/condition). Each row represents one iteration or line of the algorithm being executed.
Trace the following algorithm for n = 4:
total ← 0
i ← 1
WHILE i ≤ n DO
total ← total + i
i ← i + 1
ENDWHILE
OUTPUT total
| Step | total | i | i ≤ n? | Output |
|---|---|---|---|---|
| Start | 0 | 1 | — | — |
| Iteration 1 | 1 | 2 | True | — |
| Iteration 2 | 3 | 3 | True | — |
| Iteration 3 | 6 | 4 | True | — |
| Iteration 4 | 10 | 5 | False | 10 |
The algorithm outputs 10, which is 1+2+3+4 = 10. Correct!
If the trace table shows an unexpected value, a logic error has been found. For example, if the output above was 9 instead of 10, you could trace back through the table to find which step went wrong.
8 Edexcel-style questions · AI-marked
result ← 1 / i ← 1 / WHILE i ≤ x / result ← result * i / i ← i + 1 / ENDWHILE / OUTPUT result[4]result ← x / i ← 1 / WHILE i < n / result ← result * x / i ← i + 1 / ENDWHILE / OUTPUT result[3]total ← 0 / FOR i ← 0 TO 4 / total ← total + nums[i] / NEXT i / OUTPUT total[4]| Term | Definition |
|---|
Timed exam-style test. No feedback until submission.