In this lesson
- State a loop invariant
- Write unit tests including edge cases
Explanation
A loop invariant is a statement true before and after every iteration; it explains why a loop gives the right answer. Tests make the reasoning concrete: typical, boundary and adversarial cases.
Worked example
In a running-maximum loop the invariant is “best equals the largest of the items seen so far”; it holds initially and after each step, so at the end best is the maximum.
Practice
Write invariants and tests for functions that reverse a list in place and remove duplicates from a sorted list.