Notes

REFERENCE SHEET

Recursion, invariants & termination

A correct output and a guaranteed halt are separate obligations.

Before this Proof techniques

{P} C {Q}: if C starts in P and terminates, its final state satisfies Q

Definitions

01

Loop invariant

A statement that holds before the loop and is preserved by every iteration. Combined with the exit condition, it should imply the desired postcondition.

02

Partial vs total correctness

Partial correctness asserts the postcondition whenever the program terminates. Total correctness additionally asserts termination on every permitted input.

03

Recursive specification

A problem expressed through smaller instances, with base cases. A well-founded measure must decrease along recursive calls to justify termination.

Key theorems

01

Invariant proof rule

Establish initialization, preservation, and that invariant plus loop exit implies the postcondition. These prove partial correctness.

02

Termination by a variant

If a nonnegative integer measure strictly decreases on every iteration while the loop continues, the loop terminates.

03

Euclidean algorithm

For nonnegative integers a,b, not both zero, repeated replacement (a,b)←(b,a mod b) while b≠0 terminates with a=gcd(a₀,b₀). The gcd is invariant and the second component strictly decreases.

Notable applications

01

Search routines

A binary-search invariant specifies exactly which interval can still contain the answer.

02

Verification

State preconditions explicitly to catch overflow, invalid indices, and missing base cases.

Work it out

Try before revealing

01 / Trace

Run Euclid on (48,18).

Hint

At each step compute the remainder.

Solution

(48,18)→(18,12)→(12,6)→(6,0). The gcd is 6.

02 / Prove

For n≥0, a loop starts i=0,s=0 and repeatedly sets s←s+i+1, i←i+1 until i=n. Give an invariant and termination measure.

Hint

Relate s to the numbers processed so far.

Solution

Invariant: 0≤i≤n and s=i(i+1)/2. Initialization holds; adding i+1 establishes the formula for the next i. The nonnegative variant n−i decreases by 1. At exit s=n(n+1)/2.

Connect the ideas

Sorting, binary search & lower boundsTuring machines, deciders & recognizers

Build on this

These sheets use this topic as a prerequisite.

Sorting, binary search & lower boundsDynamic programming & greedy choiceTuring machines, deciders & recognizers

Go deeper

Further reading and full-length treatments: