4

Loop Invariants

A loop invariant is a condition that holds true before and after each iteration of a loop and after the loop exits in an algorithm.

For a computer scientist, the confirmed presence of a loop invariant will prove that the loop will (1) eventually terminate/exit (and won't become an infinite loop), and (2) produce the correct result.

Here is a detailed description of each of the stages in which the invariant must be true:

  1. Initialization: In the code right before the loop (the code that prepares the program to run the loop.)
  2. Maintenance: After the execution of each of the iterations of the loop.
  3. Termination: After the last iteration exited; that is, after the loop ended.

Let's see a couple examples of loops and their invariants.