When we use a loop (for or while), we often modify variables at each iteration. But certain properties remain true throughout the loop: these are the invariants.
We want to calculate the sum of elements in a list.
list = [2, 5, 7, 3]
sum = 0
for value in list:
sum += value
During execution, at each loop turn:
sum contains the sum of already traversed elements of the list.So, loop invariant:
sum contains the sum of elements in
listalready seen.
list = [6, 4, 9, 1]
maximum = list[0]
for element in list[1:]:
if element > maximum:
maximum = element
Here, the invariant is:
maximumcontains the largest value among those already traversed.
| Term | Meaning |
|---|---|
| Loop invariant | A property that remains true at each loop turn |
| Before the loop | The invariant is already true before the first iteration |
| After each iteration | The invariant remains true, even if variables change |
| Usefulness | Verify logic, fix a bug, or prove that the algorithm works |