SUNY Geneseo Department of Computer Science


Loop Invariants

{Date}

CSci 240, Spring 2007
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture

Misc

Lab 5 and Problem Set 8 due tomorrow

Questions?

Loop Invariants

Section 8.1

Example - sorting arrays

            i = 1
            while A[i] not in right spot
                switch A[i] with previous element
            i = i + 1
        for ( i = 1; i < A.length; i = i + 1 ) {
            // i is about to increase by one, have to prepare
            // by making sure loop invariant will still hold.
            // Do this by shifting A[i] down through A[0...i-1]
            // to put A[0 ... i] into order.
            for ( j = i; j > 0; j-- ) {
                if ( A[j] < A[j-1] ) {
                    k = A[j-1];
                    A[j-1] = A[j];
                    A[j] = k;
                }
                else {
                    break;
                }
            }
        }

Hand out Lab 6

Next

Using loop invariants (among other things) to prove loops correct

Read section 8.2 up through 8.2.3 (i.e., pages 253 bottom through 264 middle)


Next Lecture