Conceptintro
Loop invariant
Also called invariant.
A statement about the variables of a loop that is true before each step. It is the main tool to prove that a loop is correct.
In plain words
A loop changes its variables at each step. A loop invariant is a fact about these variables that does not change. It is true before the first step. Each step keeps it true. When the loop stops, the invariant and the reason for the stop together tell you that the result is correct.
The idea
To prove a loop with an invariant , you show three things:
- Start. is true before the first step.
- Step. If is true and the loop condition is true, then is true after one step.
- End. When the loop condition is false, gives the result that you want.
This is a proof by induction on the number of steps. You also need a proof that the loop stops. For this, find a variant: a non-negative integer that becomes smaller at each step.
A good invariant describes the part of the work that is done. It is often a weaker form of the result. For example, "the result" is "the full array is sorted", and the invariant is "the first items are sorted".
Examples
- In insertion sort, the invariant is: the part holds the first items of the input, in sorted order. At the end, .
- In binary search, the invariant is: if the key is in the array, it is in . The variant is .
- In merge sort, the merge loop has the invariant: the output part holds the smallest items of the two inputs, in sorted order.
- In the Euclidean algorithm, the invariant is , and the variant is .
Where it is used
Loop invariants are the base of Hoare logic, of the proofs on this site, and of tools that check programs, such as Dafny, Why3 and Lean. Programmers also write them as assertions, so that a test fails when the invariant is false.
References
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof |
| |
| Lean |
| |
| Visual |
| |
| Writing |
|
Tag 7NVRNT Edit this page History Report an error Markdown JSON