hoare-calculus program-proofing

Definition

Loop Termination

Loop termination is the proof obligation that a while loop eventually stops for all inputs satisfying the given precondition.

In Hoare calculus, termination is usually shown with a loop variant (also called a termination function): a mapping from the program state to a well-founded set, typically the natural numbers , that strictly decreases with each iteration.

Idea

A termination proof has two parts:

  • a loop invariant to show partial correctness;
  • a loop variant to show that the loop cannot continue forever.

The invariant says what stays true during the loop. The variant measures progress. Since the variant is well-founded and decreases strictly, the loop can only execute finitely many times.

Verification

For a loop while e do Π od, one typically shows:

  1. there is a variant with an initial value ;
  2. is bounded below, usually by ;
  3. every loop iteration makes strictly smaller;
  4. the invariant still holds.

A common form is:

This means that the body preserves the invariant and decreases the variant.

Alternative Formulations

Sometimes the termination obligation is written by separating the partial-correctness part from the variant condition:

and additionally showing that the variant decreases:

The second condition is what guarantees termination.

Example

Decreasing counter

Consider the following annotated loop:

{x ≥ 1}
while x > 1 do
    x := x - 1
od
{x = 1}

The loop variant is .

  • It is bounded below by the precondition .
  • It decreases by in every iteration.
  • It cannot decrease forever.

Therefore, the loop terminates.

precondition or the loop invariant. In this example, the precondition guarantees that the variant never drops below while the loop runs. Since it strictly decreases, it can only do so finitely many times.

The lower bound is not automatic. It must be derived from the

Total Correctness totally correct only if it is partially correct and its loops terminate.

A program is