A loop invariant is a statement that remains true whenever execution returns to the start of a loop. It connects the steps of an algorithm to the result you want, so you can explain correctness before relying on test results.
Worked example
Consider scanning a list for the largest value. After reading the first item, the stored best value is the largest item seen so far. Reading the next item and keeping the larger of it and best preserves that statement. When the scan finishes, every item has been seen, so best is the largest value in the list. Each comparison supports the same argument.
What to check
Decide what an empty list should mean before initializing best. An error, an optional result, and a default value are different contracts. Check the first iteration, preservation during an arbitrary iteration, and the conclusion at termination. For a list of n items, this scan uses linear time and constant extra storage.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.
Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
