There's evidence that programmers screw up when they implement iterative
Something like 20% of binary searches pass the tests we sketched
yesterday. And binary search is a well known algorithm.
Almost none of you wrote a correct binary search on your first
try. (I will say that I almost always write correct binary searches
at this point in my career, but I certainly wrote a huge number
of incorrect ones first.)
We need techniques to help us design our algorithms correctly.
We need techniques to help us assess what might be wrong with our
Something obvious: Think about the state of the program as it runs.
The settings of individual variables.
The relationships between objects.
The contents of arrays (or characteristics of the contents of
Something almost as obvious: We can draw a lot of information about
Something almost as obvious: Drawings can be ambiguous, so we may
want to rephrase them more formally.
Loop invariants apply the ideas we just suggested to the design of
We try to come up with a description of the state of the system that
meets two criteria
We can be sure that if it holds at the start of the body of the
loop, then it also holds at the end of the body of the loop.
It tells us something useful in acheiving the goals of the
We hope that if we know the loop terminates and we know the loop invariant
holds, then we've achieved the postconditions of the procedure (or at
least the code segment).
We need to figure out how to make sure that the invariant holds before
we enter the loop.
We need to make sure that the loop terminates.
It takes practice to come up with good invariants.
Note: Loop invariants are also used to prove programs correct. I find
them more useful as a tool for thinking about program design so that
we increase our odds of successful design.
We will do exercise 1 of today's lab collaboratively.
You can try exercises 2 and 3 of today's lab with your partner.