CSC 288 · Structured Programming
Our notes
1 min readAssertions
An assertion is a statement about the program's variables that must be true at a point.
- Precondition: true before a piece of code runs (n >= 0).
- Postcondition: what the code guarantees afterwards (sum = 1 + 2 + ... + n).
The loop invariant
An invariant is a condition that is true before the loop starts, after every pass, and therefore when it ends. Combined with the exit condition, it gives the postcondition.
To prove a loop correct:
- Initialisation: the invariant holds before the first pass.
- Maintenance: if it holds before a pass, it holds after it.
- Termination: when the loop stops, invariant + exit condition give the result.
- Progress: something (a variant) decreases each pass and cannot go below a bound, so the loop ends.
Worked example: summing 1 to n
sum := 0; i := 0;
while i < n do
begin
i := i + 1;
sum := sum + i
end;
- Invariant: sum = 1 + 2 + ... + i (and 0 <= i <= n).
- Initially i = 0 and sum = 0 (empty sum): holds.
- Each pass increases i by 1 and adds the new i to sum: still holds.
- At exit i = n (since i < n is false and i <= n), so sum = 1 + ... + n = n(n + 1)/2.
- Variant: n − i decreases by 1 each pass and stops at 0.
Worked example: largest element
max := a[1]; i := 1;
while i < n do
begin
i := i + 1;
if a[i] > max then max := a[i]
end;
Invariant: max is the largest of a[1..i]. At exit i = n, so max is the largest of the whole array.
Why it matters
- Writing the invariant first often tells you how to write the loop.
- It catches off-by-one errors: if the invariant says a[1..i] but the loop starts at i = 0, something is wrong.
- Program verification (proving programs correct) rests on these ideas (Hoare logic, 1969).
Exams usually ask
- Define precondition, postcondition and loop invariant.
- State and verify an invariant for a given loop.
- Show that a loop terminates.
Common mistake
Giving the exit condition as the invariant. The invariant must be true on every pass; "i = n" is true only at the end.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.