Sub topic 9
Tracing an Algorithm by Hand
This chapter assumes you can read short Python functions and the pseudocode style used earlier in the tutorial. It also assumes you are comfortable with the remainder operator (mod in pseudocode, % in Python). You have already seen Euclid's algorithm written in plain language, pseudocode and Python. Here you will run it yourself, on paper, one step at a time.
What Tracing Is and Why It Matters
Tracing an algorithm means executing it by hand on a specific input. You record the value of every variable after each step. You act as the computer: you follow each instruction literally, without skipping ahead and without using what you "know" the answer should be.
Tracing does three jobs:
- It checks your understanding. If you cannot predict what the next line does, you do not yet understand the description.
- It finds bugs before code exists. A trace of pseudocode can expose a wrong loop condition or a missing case while the fix is still cheap.
- It prepares correctness arguments. The pattern you see across rows of a trace often points to the loop invariant you will need later.
A trace proves nothing about inputs you did not try. It is evidence, not proof. One well-chosen trace still catches a large share of everyday mistakes.
The State Table
The state of an algorithm is the set of current values of all its variables. A state table records that state over time. Each column is a variable. Each row is a moment you have chosen to record. The usual moment is the point where the loop condition is about to be tested.
Choosing that moment matters. If you record at the top of the loop, every row shows a state where the condition gets checked. The last row is the state that fails the check and ends the loop. This makes the exit visible in the table itself.
Here is the pseudocode we will trace:
function GCD(a, b)
// Precondition: a >= 0, b >= 0, not both zero
// Postcondition: returns gcd(a, b)
while b != 0 do
r <- a mod b
a <- b
b <- r
end while
return a
end functionWorked Trace: GCD(48, 18)
Start with the inputs a = 48 and b = 18. Before each test of b != 0, write one row. Add a column for r, which is undefined until the first pass through the loop body.
| Check | a | b | r (from previous pass) | b != 0? |
|---|---|---|---|---|
| 1 | 48 | 18 | — | yes |
| 2 | 18 | 12 | 12 | yes |
| 3 | 12 | 6 | 6 | yes |
| 4 | 6 | 0 | 0 | no |
Walk through the step from check 1 to check 2 slowly:
r <- 48 mod 18. 18 goes into 48 twice (36), leaving 12, so r = 12.a <- bsets a to 18.b <- rsets b to 12.
At check 4, b is 0, so the loop exits and the function returns a = 6. The sequence of (a, b) pairs is (48, 18), (18, 12), (12, 6), (6, 0). The loop body ran three times. There are four rows because the condition is tested once more than the body runs.
Tracing Edge Cases
Typical inputs show that the algorithm usually works. Edge cases show where it breaks. When you trace, pick inputs that hit the boundaries of the precondition and the unusual paths through the control structures.
When a is smaller than b
Trace GCD(18, 48):
| Check | a | b | b != 0? |
|---|---|---|---|
| 1 | 18 | 48 | yes |
| 2 | 48 | 18 | yes |
| 3 | 18 | 12 | yes |
| 4 | 12 | 6 | yes |
| 5 | 6 | 0 | no |
In the first pass, 18 mod 48 is 18, because 48 goes into 18 zero times. The assignments then swap a and b. The algorithm needs no special case for a < b. It spends one extra iteration fixing the order. You only find this out by tracing it.
When the loop body never runs
Trace GCD(7, 0). At check 1, b is already 0, so the loop body runs zero times and the function returns 7. The table has a single row. Many off-by-one bugs live here, so always trace at least one input where a loop runs zero times.
When a is zero
Trace GCD(0, 5). At check 1, b = 5 is non-zero. Then r = 0 mod 5 = 0, a becomes 5 and b becomes 0. At check 2 the loop exits and returns 5, which is correct because every integer divides 0.
| Input | Body executions | Result | What it tests |
|---|---|---|---|
| (48, 18) | 3 | 6 | Typical case |
| (18, 48) | 4 | 6 | Arguments in "wrong" order |
| (7, 0) | 0 | 7 | Loop skipped entirely |
| (0, 5) | 1 | 5 | Zero as first argument |
Tracing Selection: Linear Search
Loops with an if inside need one more column: which branch was taken. Here is linear search:
def linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1Trace linear_search([7, 3, 9, 3], 3):
| i | x | x == target? | Action |
|---|---|---|---|
| 0 | 7 | no | continue |
| 1 | 3 | yes | return 1 |
The trace stops at i = 1. The second 3 at index 3 is never examined. The trace shows that the function returns the first match, which is a fact about behaviour you would want in its specification.
Now trace linear_search([7, 3, 9, 3], 5). All four rows answer "no", the loop ends, and the function returns -1 after four comparisons. Tracing both the "found" and "not found" paths covers both exits from the function.
A Common Trap: Order of Assignment
Pseudocode runs its assignments one at a time, in order. Python's tuple assignment a, b = b, a % b evaluates the whole right-hand side first and then assigns. A trace exposes what happens if you mix the two up. Suppose someone "simplifies" the loop body to:
def gcd_buggy(a, b):
while b != 0:
a = b
b = a % b
return a
print(gcd_buggy(48, 18)) # prints 18, not 6Trace it from (48, 18). The line a = b sets a to 18. Then b = a % b computes 18 % 18 = 0, because a has already changed. The loop exits and returns 18. The original pseudocode avoids this by saving the remainder in r before overwriting anything. The Python version avoids it by evaluating b, a % b before either assignment happens.
Checking a Hand Trace with an Instrumented Program
After you trace by hand, you can confirm the table by making the program print its own state. Put a print at the same point where you recorded rows, at the loop test:
def gcd_traced(a, b):
print(f"{'step':>4} {'a':>4} {'b':>4} {'a % b':>6}")
step = 0
while b != 0:
print(f"{step:>4} {a:>4} {b:>4} {a % b:>6}")
a, b = b, a % b
step += 1
print(f"{step:>4} {a:>4} {b:>4} {'-':>6}")
return a
print(gcd_traced(48, 18))Output:
step a b a % b
0 48 18 12
1 18 12 6
2 12 6 0
3 6 0 -
6If your hand trace and the printed trace disagree, one of them has a mistake. Find out which one before you move on. An instrumented trace does not replace a hand trace. The point of tracing by hand is to build your own model of the algorithm, and reading output does not build it.
Habits of a Good Trace
- Decide in advance where rows are recorded, and record them only there.
- Include a column for every variable, including temporaries such as
r. - For loops, record the condition result. For selections, record the branch taken.
- Choose inputs that run a loop zero times, once, and several times.
- Choose inputs at the edges of the precondition, such as zero, equal values and the smallest allowed list.
- Compare the final row against the postcondition, not against the answer you expected.
Exercise
Trace the pseudocode GCD(252, 105) with a state table that records a, b and the result of the loop test before each test. How many times does the loop body run, and what is returned?
Show answer
Rows: (252, 105, yes) → r = 42 → (105, 42, yes) → r = 21 → (42, 21, yes) → r = 0 → (21, 0, no). The body runs 3 times and the function returns 21.
Exercise
Trace find_max([4, 9, 2, 9, 11]), where best starts at xs[0] and the loop updates best only when x > best. Give the value of best after each element of xs[1:] is processed, and say whether the second 9 changes best.
Show answer
best starts at 4. After x = 9: best = 9. After x = 2: best = 9. After x = 9: best = 9, because 9 > 9 is false, so the second 9 changes nothing. After x = 11: best = 11. The function returns 11.
Exercise
Trace gcd_buggy(10, 4). What does it return, and which line causes the wrong answer?
Show answer
a = b sets a to 4, then b = a % b computes 4 % 4 = 0. The loop exits and returns 4, but gcd(10, 4) is 2. The bug is in b = a % b, which reads the new value of a instead of the original one.
Exercise
You want a minimal set of inputs for tracing GCD that runs the loop body zero times, exactly once, and more than once. Give one input for each.
Show answer
Zero times: (7, 0). Exactly once: (0, 5) or (12, 6), since 12 mod 6 = 0. More than once: (48, 18), which runs three times.