A Small Worked Loop Invariant
A loop invariant is a claim true before the loop and after every iteration. It links current state with the part of the input already processed.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Start with an empty prefix
For a running count of even values, after \(i\) steps the count equals the even entries among the first \(i\). Before work, both values are zero. This uses loop counters with a precise meaning.
Check one update
Reading an odd item leaves the count unchanged and lengthens the visited prefix. An even item increments the count. At exit the prefix is the whole list. Loop invariants extend this proof pattern to a boundary search.[1]
State a claim about the processed prefix
To compute the largest element of a nonempty list, initialize with the first item. Before inspecting index \(i\), the current maximum equals the maximum on positions below \(i\). Comparing the next element with the stored one makes the claim true for the enlarged prefix. See function postconditions.
Start with [4] → maximum 4
Extend to [4,9] → maximum 9
Extend to [4,9,2] → maximum 9
Extend to [4,9,2,7] → maximum 9
Use initialization, preservation and exit explicitly
Initialization must be valid even on all-negative data. Preservation uses one comparison. At exit the processed prefix is the whole input, giving the desired postcondition. A separate decreasing measure shows that the loop reaches that exit.