Back to Worked Examples
Algorithms Term 3
Trace Tables
Problem Statement
Complete a trace table for the following algorithm that calculates the factorial of a number. Use the input value n = 4.
BEGIN Factorial
INPUT n
result = 1
counter = 1
WHILE counter <= n
result = result * counter
counter = counter + 1
ENDWHILE
OUTPUT result
END Step-by-Step Solution
1
Identify all variables
List every variable used in the algorithm. These become your column headers.
Variables found:
n- the input numberresult- stores the factorial being calculatedcounter- loop counter
Also track:
counter <= n- the loop condition (TRUE/FALSE)Output- what gets displayed
2
Set up the trace table
Create columns for each variable, the condition, and output. Add a row number column.
| Step | n | result | counter | counter <= n | Output |
|---|---|---|---|---|---|
| ... |
3
Trace through initialization
Record the initial values before the loop starts.
INPUT n // n = 4
result = 1 // result = 1
counter = 1 // counter = 1 | Step | n | result | counter | counter <= n | Output |
|---|---|---|---|---|---|
| 1 | 4 | 1 | 1 | - | - |
4
Trace each loop iteration
For each iteration: check condition, execute body, update variables.
Iteration 1:
- Check: Is 1 <= 4? TRUE (enter loop)
- result = 1 * 1 = 1
- counter = 1 + 1 = 2
Iteration 2:
- Check: Is 2 <= 4? TRUE (continue loop)
- result = 1 * 2 = 2
- counter = 2 + 1 = 3
Iteration 3:
- Check: Is 3 <= 4? TRUE (continue loop)
- result = 2 * 3 = 6
- counter = 3 + 1 = 4
Iteration 4:
- Check: Is 4 <= 4? TRUE (continue loop)
- result = 6 * 4 = 24
- counter = 4 + 1 = 5
Exit check:
- Check: Is 5 <= 4? FALSE (exit loop)
- OUTPUT result → 24
Complete Trace Table
| Step | n | result | counter | counter <= n | Output |
|---|---|---|---|---|---|
| 1 (init) | 4 | 1 | 1 | - | - |
| 2 | 4 | 1 | 1 | TRUE | - |
| 3 | 4 | 1 | 2 | - | - |
| 4 | 4 | 1 | 2 | TRUE | - |
| 5 | 4 | 2 | 3 | - | - |
| 6 | 4 | 2 | 3 | TRUE | - |
| 7 | 4 | 6 | 4 | - | - |
| 8 | 4 | 6 | 4 | TRUE | - |
| 9 | 4 | 24 | 5 | - | - |
| 10 | 4 | 24 | 5 | FALSE | - |
| 11 | 4 | 24 | 5 | - | 24 |
Result: The factorial of 4 is 24 (4! = 4 × 3 × 2 × 1 = 24)
Tips for Trace Tables
- ✓ Only update values that actually change in each step
- ✓ Check the loop condition BEFORE each iteration
- ✓ Use a dash (-) for values that haven't been set yet or don't apply
- ✓ Verify your final answer makes sense (4! should equal 24)
Common Mistakes to Avoid
- ✗ Forgetting to check the condition before each loop iteration
- ✗ Using the OLD value of a variable after it's been updated
- ✗ Missing the final condition check that exits the loop
- ✗ Not including all variables (especially the loop counter)