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:
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.
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 }
]|