Sub topic 14
Reasoning with Loop Invariants
This chapter assumes you can already build trace tables, trace loops one iteration at a time, and desk check pseudocode for off-by-one errors. It reuses FindMax, the summing loop, and InsertionSort from earlier chapters.
A trace shows that a loop works for one input. A loop invariant lets you argue that it works for every input. The two methods support each other: traces help you guess an invariant, and the invariant tells you what each row of a trace should look like.
What a Loop Invariant Is
A loop invariant is a statement about the loop's variables that is true every time control reaches the loop test. "Every time" includes the first arrival, before the body has run at all, and the last one, when the test fails and the loop exits.
A useful invariant usually describes partial progress: "the work done so far is correct for the part of the input already processed." When the loop ends, the processed part is the whole input, so the partial result becomes the full answer.
The Three Checks
To use an invariant, you check three things. They are the same steps as a proof by induction, applied to a loop.
| Check | Question to answer | Where you look |
|---|---|---|
| Initialization | Is the invariant true before the first iteration? | The assignments just before the loop |
| Maintenance | If it is true at the start of an iteration, is it still true at the start of the next one? | The loop body, including the update of the loop variable |
| Termination | When the loop exits, does the invariant plus the exit condition give the result you want? | The loop condition and the final value of the loop variable |
Example 1: FindMax
Here is FindMax again:
FUNCTION FindMax(A, n)
max ← A[1]
FOR i ← 2 TO n DO
IF A[i] > max THEN
max ← A[i]
END IF
END FOR
RETURN max
END FUNCTIONThe invariant: at the start of each iteration, max equals the largest value in A[1..i-1].
- Initialization. Before the first iteration,
i = 2andmax = A[1]. The largest value inA[1..1]isA[1], so the invariant holds. - Maintenance. Assume
maxis the largest value inA[1..i-1]. IfA[i] > max, thenA[i]is larger than everything before it, andmaxbecomesA[i]. Otherwisemaxstays the same and is still at least as large asA[i]. Either way,maxis now the largest value inA[1..i]. TheFORthen increasesiby one, so the statement reads "largest inA[1..i-1]" again. - Termination. The loop exits when
ipassesn, soi = n + 1. Substituting into the invariant gives "maxis the largest value inA[1..n]", which is the whole array.
Compare this with the trace table for A = [3, 7, 2, 9]:
| Arrival at test | i | A[1..i-1] | max | Invariant holds? |
|---|---|---|---|---|
| 1st | 2 | [3] | 3 | yes |
| 2nd | 3 | [3, 7] | 7 | yes |
| 3rd | 4 | [3, 7, 2] | 7 | yes |
| exit | 5 | [3, 7, 2, 9] | 9 | yes |
Adding an "invariant holds?" column to a trace table is a good habit. If any row says "no", either the code or your invariant is wrong. In both cases you have learned something.
Example 2: Catching the Off-by-One Without a Trace
The desk-checking chapter found this bug by tracing n = 3:
total ← 0
i ← 1
WHILE i < n DO
total ← total + i
i ← i + 1
END WHILE
RETURN totalWrite down the intended invariant: total = 1 + 2 + … + (i - 1).
- Initialization. With
i = 1the sum is empty, which equals 0, andtotal = 0. The invariant holds. - Maintenance. Adding
igives1 + … + i. Increasingithen turns that back into1 + … + (i - 1). The invariant holds. - Termination. The loop exits when
i < nbecomes false. Forn ≥ 1, that first happens ati = n. The invariant then saystotal = 1 + … + (n - 1).
The termination check fails. The loop's result is missing n, and you found this without picking an input. Changing the condition to i ≤ n moves the exit to i = n + 1, which gives total = 1 + … + n. Check the edge case too. With n = 0 the loop never runs and total = 0, which is the correct empty sum.
Initialization and maintenance both passed here. Bugs in loop bounds almost always show up at termination, so check that step most carefully.
Example 3: The Outer Loop of Insertion Sort
PROCEDURE InsertionSort(A, n)
FOR j ← 2 TO n DO
key ← A[j]
i ← j - 1
WHILE i ≥ 1 AND A[i] > key DO
A[i + 1] ← A[i]
i ← i - 1
END WHILE
A[i + 1] ← key
END FOR
END PROCEDUREThe invariant: at the start of each outer iteration, A[1..j-1] holds the elements that were originally in A[1..j-1], in sorted order.
- Initialization. When
j = 2, the subarrayA[1..1]has one element, and a single element is always sorted. - Maintenance. The inner loop moves every element of
A[1..j-1]that is greater thankeyone place to the right. It stops at the first element not greater thankey, or at the left end. Writingkeyinto the gap leavesA[1..j]sorted and holding the original firstjelements. A full argument would give the inner loop its own invariant. For hand reasoning, this informal step is usually enough. - Termination. The loop exits at
j = n + 1, soA[1..n]holds the original elements in sorted order.
The phrase "the elements originally in" matters. Without it, the invariant only says "A[1..j-1] is sorted". A broken body that wrote 0 into every cell would satisfy that weaker statement. Correctness for a sort means the output is sorted and is a rearrangement of the input.
Checking an Invariant While the Code Runs
Once you translate pseudocode into a real language, you can turn the invariant into an assertion. Remember the index shift: with 0-based indexing, "A[1..i-1]" becomes the slice a[:i].
def find_max(a):
max_val = a[0]
for i in range(1, len(a)):
# Invariant: max_val is the largest value in a[0..i-1]
assert max_val == max(a[:i])
if a[i] > max_val:
max_val = a[i]
# Termination: the invariant now covers the whole list
assert max_val == max(a)
return max_val
print(find_max([3, 7, 2, 9])) # 9
print(find_max([5])) # 5These assertions use the built-in max, so they cost far more than the function they check. Use checks like this while testing or teaching, and take them out of production code.
Common Mistakes
- An invariant that is too weak. "
maxis some element ofA" is true at every test, but at exit it does not show thatmaxis the largest. An invariant must be strong enough to give the result at termination. - An invariant that is false at the start. "
maxis the largest inA[1..i]" fails at initialization, becauseA[2]has not been examined yet. This kind of off-by-one in the invariant often matches an off-by-one in the code. - Checking at the wrong point. An invariant can be false partway through the body. In insertion sort, the array briefly holds a duplicate while elements shift right. The invariant only has to hold at the loop test.
- Confusing the invariant with the loop condition.
i ≤ nis the condition that keeps the loop running. The invariant describes what the loop has achieved so far. - Skipping termination. Many people prove maintenance carefully and then assume the exit works. Example 2 shows why you should check it.
When to Write One Down
You do not need a written invariant for every loop. Write one when a loop updates several variables that depend on each other, when the bounds are hard to get right, when the loop changes an array in place, or when a trace passes but you still doubt the loop works. A one-line comment stating the invariant above a loop also helps whoever reads the code next.
Exercise
This loop counts the even values in A[1..n]. State an invariant for it and use the termination check to show that it returns the right count. count ← 0 k ← 1 WHILE k ≤ n DO IF A[k] MOD 2 = 0 THEN count ← count + 1 END IF k ← k + 1 END WHILE RETURN count
Show answer
Invariant: count equals the number of even values in A[1..k-1]. Initialization: with k = 1 the range is empty and count = 0. Maintenance: count goes up by one exactly when A[k] is even, so it now covers A[1..k], and increasing k restores the form A[1..k-1]. Termination: the loop exits when k ≤ n is false, so k = n + 1, and count is the number of even values in A[1..n].
Exercise
Someone proposes "max ≥ A[1]" as the invariant for FindMax. Which of the three checks does it pass, and why is it still not good enough?
Show answer
It passes initialization, because max = A[1]. It passes maintenance, because max never decreases. At termination it only tells you that max ≥ A[1], not that max is at least every element of A, so it cannot show the function is correct. The invariant is too weak.
Exercise
In the fixed sum loop (condition i ≤ n), what are the exit value of i and the value of total when n = 0? Does the invariant still give the correct result?
Show answer
The test 1 ≤ 0 is false right away, so the body never runs. i stays at 1 = n + 1 and total = 0. The invariant says total = 1 + … + (i − 1) = 1 + … + 0, which is the empty sum 0. That is the correct answer, so the invariant holds for this edge case.