Science Fair Project Encyclopedia
This rule is a deductive step that has as its premise the Hoare triple . This triple is actually a relation on machine states. It holds whenever starting from a state in which the boolean expression is true and successfully executing some program called body, the machine ends up in a state in which I is true. If this relation can be proven, the rule then allows us to conclude that successful execution of the program
while (C) body will lead from a state in which I is true to a state in which holds. The boolean formula I in this rule is known as the loop invariant.
The following example illustrates how this rule works. Consider the program
while (x<10) x:= x+1;
One can then prove the following Hoare triple:
The condition C of the
while loop is x < 10. A useful loop invariant I is . Under these assumptions it is possible to prove the following Hoare triple:
While this triple can be derived formally from the rules of Floyd-Hoare logic governing assignment, it is also intuitively justified: Computation starts in a state where is true, which means simply that x < 10 is true. The computation adds 1 to x, which means that is still true.
Under this premise, the rule for
while loops permits the following conclusion:
However, the post-condition (x is less than or equal to 10, but it is not less than 10) is logically equivalent to x = 10, which is what we wanted to show.
The loop invariant plays an important role in the intuitive argument for soundness of the Floyd-Hoare rule for
while loops. The loop invariant has to be true before each iteration of the loop body, and also after each iteration of the loop body. Since a
while loop is precisely the repeated iteration of the loop body, it follows that if the invariant is true before entering the loop, it must also be true after exiting the loop.
Because of the fundamental similarity of loops and recursive programs, proving partial correctness of loops with invariants is very similar to proving correctness of recursive programs via induction. In fact, the loop invariant is often the inductive property one has to prove of a recursive program that is equivalent to a given loop.
The contents of this article is licensed from www.wikipedia.org under the GNU Free Documentation License. Click here to see the transparent copy and copyright details