SE 504
Spring 2009
HW # 6: Repetition
Due: March 26

In each problem, you are given a Hoare triple of the form {P} Sinit; LOOP {Q} in which Sinit is an assignment command (used for initialization) and LOOP is a repetition command annotated with a loop invariant and bound function, as in this template:

   {loop invariant I: ... }
   {bound function t: ... }
   do B1 → S1 
   [] B2 → S2 
   ...
   [] Bm → Sm 
   od

Prove it by showing each of the five items on the loop checklist:

  1. {P} Sinit {I}, which guarantees that the initialization establishes the loop invariant (just before the loop's first iteration).
  2. {I ∧ Bi} Si {I} (for each i satisfying 1 ≤ i &le m), which guarantees that each iteration of the loop preserves the truth of the loop invariant.
  3. I ∧ ¬(B1 ∨ ... ∨ Bm)  ⇒  Q, which guarantees that, if the loop terminates, the postcondition will hold at that time.
  4. I ∧ (B1 ∨ ... ∨ Bm)  ⇒  t > 0, which guarantees that, as long as more iterations are to occur, the bound function has not yet descended to its threshold of zero.
  5. {I ∧ Bi ∧ t=C} Si {t < C} (for each i satisfying 1 ≤ i &le m), which guarantees that each iteration of the loop causes the value of the bound function to decrease.

Items 1 and 2 together show that I is, as claimed, an invariant of the loop. Item 3 shows that, if and when the loop terminates, the postcondition Q holds. Items 4 and 5 together show that the loop eventually terminates.

Note that any precondition regarding only constants (e.g., N ≥ 0) can be considered as an implicit part of the loop invariant.


1. This program computes the N-th Fibonacci number, placing the result in the variable this. The Fibonacci numbers are defined as follows:

f.0 = 0, f.1 = 1, and, for k>1, f.k = f.(k-1) + f.(k-2)

Prove the program's correctness.


   |[ con N : int; 
      var i,this,next : int; 
      {P: N ≥ 0}
      this, next, i := 0, 1, 0;
      {loop invariant I: 0≤i≤N  ∧  this = f.i  ∧  next = f.(i+1)}
      {bound t: N-i}
      do i ≠ N  →  i, this, next := i+1, next, this + next 
      od
      {Q: this = f.N}
   ]|

2. Prove the correctness of this program, which calculates 2Y + X in a very roundabout way.

   |[ con X, Y : int;
      var x,y,z : int;
      {P: X ≥ 0  ∧  Y ≥ 0}
      x,y,z := X,Y,0;
      {loop invariant I: z = 2(Y-y) + (X-x)  ∧  x ≥ 0  ∧  y ≥ 0 }
      {bound t: 2y + x}
      do x > y  →  x,z := x-1,z+1
      [] y > 0  →  x,y := x+1,y-1; z := z+1
      od
      {Q: z = 2Y + X }
   ]|