Sub topic 8
Tracing Loops Iteration by Iteration
A loop runs the same few lines many times, and each pass leaves the variables in a slightly different state. Most bugs in iterative algorithms show up as a wrong value in one particular pass, or as a loop that runs once too often or never stops. This chapter shows a disciplined way to trace FOR, WHILE, and REPEAT ... UNTIL loops so those bugs appear on paper.
This chapter assumes you can read the pseudocode conventions from earlier chapters (← for assignment, END keywords, 1-based arrays), and that you know the trace table layout: one column per variable, one row per step. Nested loops, choosing inputs, and desk checking for logic errors each get their own chapter. Here the focus is on a single loop: what happens on each pass, when the loop ends, and how to be sure that it ends.
What a Loop Trace Must Capture
A trace of straight-line code records one row per statement. That gets unreadable for loops, so the usual convention is one row per iteration, plus two extra rows:
- An init row with the values just before the loop starts.
- One row per iteration, showing the condition result that let the iteration run and the variable values after the body finishes.
- A final test row showing the condition evaluating to false, which is why the loop stopped.
The final test row is the one people skip, and it is the one that catches off-by-one errors. If you can't write down the exact comparison that came out false, you haven't finished the trace.
Tracing a WHILE Loop
A WHILE loop tests its condition before every pass, including the first. Here is a loop that sums the decimal digits of a positive integer:
FUNCTION DigitSum(n)
total ← 0
WHILE n > 0 DO
total ← total + (n MOD 10)
n ← n DIV 10
END WHILE
RETURN total
END FUNCTIONMOD gives the remainder and DIV gives integer division that discards the fraction. Trace it with n = 4072:
step | n before | n > 0 | n MOD 10 | total | n after
------+----------+-------+----------+-------+--------
init | - | - | - | 0 | 4072
1 | 4072 | true | 2 | 2 | 407
2 | 407 | true | 7 | 9 | 40
3 | 40 | true | 0 | 9 | 4
4 | 4 | true | 4 | 13 | 0
final | 0 | false | - | 13 | 0
Returns 13A few habits are visible in this table:
- Columns for intermediate expressions.
n MOD 10isn't a variable, but giving it a column stops you from doing the arithmetic in your head and getting it wrong. - Before and after columns for the controlling variable. The condition reads
nbefore the body runs. The next row's condition readsnafter the body runs. Showing both makes the hand-off between iterations explicit. - Statement order inside the body matters.
totaluses the oldn, and thennis updated. If you swapped the two lines, step 1 would add407 MOD 10 = 7and the final answer would be wrong. Trace the statements in the order they are written, never in the order you expect them to run.
The result checks out: 4 + 0 + 7 + 2 = 13.
Tracing a FOR Loop
A counted FOR loop hides its condition and its increment. To trace one, rewrite it in your head as the equivalent WHILE:
FOR i ← a TO b DO
body
END FOR
// behaves like:
i ← a
WHILE i ≤ b DO
body
i ← i + 1
END WHILESome consequences follow from this:
- The body runs
b - a + 1times whenb ≥ a, and zero times whenb < a.FOR k ← 5 TO 2never runs its body. - Treat the bounds as evaluated once, at the start. If the body changes
b, many languages ignore the change, but some don't. Good pseudocode never modifies the bounds or the loop variable inside the body. If you see that happen during a trace, flag it. - The value of
iafter the loop isn't reliable across languages. In theWHILEform it ends atb + 1, while a Pythonforleaves it atb. Don't write pseudocode that depends on it. Record the exit value in the trace anyway, labelled as convention-dependent.
For a FOR loop, you can often drop the condition column and list i per row, because the loop count is fixed in advance. Keep the final test row when the bounds come from input, because that row is where n = 0 or n = 1 problems show up.
Post-Test Loops: REPEAT ... UNTIL
REPEAT ... UNTIL runs the body first and then tests. It stops when the condition becomes true, which is the opposite of WHILE.
count ← 0
x ← 0
REPEAT
x ← x + 5
count ← count + 1
UNTIL x ≥ 12step | x | count | x ≥ 12
-----+----+-------+-------
init | 0 | 0 | -
1 | 5 | 1 | false
2 | 10 | 2 | false
3 | 15 | 3 | true -> exitHere the condition column comes after the body's values in each row, because that is when the test happens. The body always runs at least once. If x started at 100, a WHILE x < 12 loop would do nothing, but this loop would still run once and leave count = 1. When you translate between the two forms, trace the case where the condition is already satisfied before the first pass.
Will It Terminate?
A trace with ten rows tells you the loop stopped for that input. It doesn't show that the loop stops for every input. To argue termination, find a variant: a whole-number quantity that strictly decreases on every iteration and can't drop below some bound while the loop keeps running.
- In
DigitSum, the variant isn. Whenn > 0,n DIV 10 < n, andnnever goes negative, so the loop must stop. - In a
FOR i ← a TO bloop, the variant isb - i + 1, which shrinks by one each pass.
When no variant exists, the trace usually shows it as a pattern:
i ← 1
WHILE i ≠ 10 DO
i ← i + 2
END WHILEstep | i before | i ≠ 10 | i after
-----+----------+--------+--------
init | - | - | 1
1 | 1 | true | 3
2 | 3 | true | 5
3 | 5 | true | 7
4 | 7 | true | 9
5 | 9 | true | 11
6 | 11 | true | 13i takes only odd values, so it jumps from 9 to 11 and never equals 10. The distance to 10 shrinks and then grows again, so it is not a variant. The fix is to use an ordering test such as i < 10 instead of an equality test whenever the step is larger than 1.
Compound Conditions and Early Exit
Loops that search often have two exit reasons:
i ← 1
WHILE i ≤ n AND A[i] ≠ target DO
i ← i + 1
END WHILEGive each part of the condition its own column, so the final test row shows which part became false. If i ≤ n failed, the target is absent. If A[i] ≠ target failed, it was found at i. Assume AND short-circuits: when i = n + 1, the first part is false and A[n + 1] is never read. Write "not evaluated" in that cell rather than inventing a value.
Confirming a Trace by Instrumenting Code
Once your hand trace is done, you can check it by printing the same columns from a real run. This Python version prints the DigitSum table:
def digit_sum(n):
total = 0
print(f"{'step':>5} | {'n before':>8} | {'n > 0':>5} | {'total':>5} | {'n after':>7}")
print(f"{'init':>5} | {'-':>8} | {'-':>5} | {total:>5} | {n:>7}")
step = 0
while n > 0:
before = n
total += n % 10
n //= 10
step += 1
print(f"{step:>5} | {before:>8} | {'true':>5} | {total:>5} | {n:>7}")
print(f"{'final':>5} | {n:>8} | {'false':>5} | {total:>5} | {n:>7}")
return total
print(digit_sum(4072)) # 13The printed rows should match your table exactly. If they don't, find the first row that differs. Either your trace or your understanding of a statement is wrong at that point.
Common Loop-Tracing Mistakes
| Mistake | What it looks like | How to avoid it |
|---|---|---|
| Skipping the final test | Trace ends after the last "true" row | Always write the row where the condition is false |
| Reordering body statements | Using the new value of a variable too early | Trace line by line, in written order |
| Assuming a FOR loop runs at least once | Missing the `b < a` case | Compute `b - a + 1` before tracing |
| Confusing UNTIL with WHILE | Exiting when the condition is false | Remember that UNTIL exits on true |
| Treating a long trace as proof of termination | Many rows, no argument | Name a variant that strictly decreases |
| Reading past the array end | Evaluating `A[n + 1]` | Apply short-circuit evaluation and mark "not evaluated" |
Exercises
Exercise
How many times does the body of FOR k ← 5 TO 2 DO ... END FOR run, and how many times does FOR k ← 2 TO 2 run?
Show answer
The first runs 0 times because 2 < 5 (b - a + 1 = -2, which means no iterations). The second runs exactly once, since 2 - 2 + 1 = 1.
Exercise
Trace x ← 20; c ← 0; WHILE x > 1 DO x ← x DIV 2; c ← c + 1 END WHILE. Give the value of x after each iteration, the final test, and the final value of c.
Show answer
x goes 20 → 10 (c = 1) → 5 (c = 2) → 2 (c = 3) → 1 (c = 4). Final test: 1 > 1 is false, so the loop stops with c = 4.
Exercise
Does i ← 0; WHILE i ≠ 9 DO i ← i + 3 END WHILE terminate? What if i starts at 1? Suggest a condition that terminates in both cases.
Show answer
Starting at 0, i goes 0, 3, 6, 9 and stops after 3 iterations. Starting at 1, i goes 1, 4, 7, 10, 13, ... and never equals 9, so the loop never ends. Using WHILE i < 9 terminates in both cases, because 9 - i is a variant that decreases by 3 each pass.
Exercise
Trace REPEAT x ← x × 2 UNTIL x > 10 with x starting at 50. How many times does the body run, and what is x at the end? What would a WHILE x ≤ 10 loop with the same body do?
Show answer
The REPEAT body runs once, giving x = 100. Then 100 > 10 is true, so the loop exits. The WHILE version tests 50 ≤ 10 first, finds it false, runs zero times, and leaves x = 50.