Reading material

Pages 211-214 (Section 5.4) and pages 109-110 (Section 3.4.3)

Loop invariants

Pre- and postconditions are predicates. Both tell us something about the values of the variables of our programs. For example, `n = 1' and `list is nonempty' are such predicates. We use
     { P } S { Q }
to specify that
     if the variables have values such that the predicate P is satisfied at the start of the execution of statement S
     and the execution of the statement S terminates
     then at termination the variables have values such that the predicate Q is satisfied.
For example,
     { n = 0 } n = n + 1; { n = 1 }
and
     { true } list.insertLast("x"); { list is nonempty }

A loop invariant is also a predicate. It tells us something about the values of the variables while executing a loop. This predicate should be satisfied at the beginning of every iteration of the loop. Consider the loop
     while B do S
with loop invariant LI. If
     { LI B } S { LI },
that is, statement S preserves the loop invariant LI within the loop, then we can conclude that
     { LI } while B do S { LI B },
that is, if the loop invariant LI is satisfied at the start of the execution of the loop and the loop terminates then the loop invariant LI (and of course also B) is satisfied at termination.

Consider the following Java snippet.

int i = 1;
int x = 1;
while (i < N)
{
    x *= i + 1;
    i++;
}
For the above loop, the assertion x = i! i <= N is a loop invariant.

Algorithm bubbleSort(sequence):
   Input: sequence of integers sequence
   Postcondition: sequence is sorted and contains the same integers as the original sequence
length length of sequence
i 0
while i < length do
     j 0
     while j < length - 1 do
         if jth element of sequence > (j+1)th element of sequence then
             swap jth and (j+1)th element of sequence

The outer loop has loop invariant
(A k : length - i <= k < length : (A l : k < l < length : kth element of sequence <= lth element of sequence))
and the inner loop has loop invariant
(A k : length - i <= k < length : (A l : k < l < length : kth element of sequence <= lth element of sequence))
(A k : 0 <= k < j : kth element of sequence <= jth element of sequence)

Question

Consider the following main method.
public static void main(String[] args) 
{
    int lo = 1;
    int hi = 1;
    int n = Integer.parseInt(args[0]);
    int i = 1;
    while (i < n)
    { 
        int temp = hi;
	hi = lo + hi;
        lo = temp; 
	i++;    
    }
    System.out.println(hi);
}
Try to come up with a loop invariant.