How can I demonstrate through Hoare logic the correctness of a program that has a while cycle. It would be fascinating that some one develop it with any example, due to as my problem to solve is:
Precondition={n>0}
cont := n;
sum := 0;
while cont <> 0 do:
sum := sum + cont;
cont := cont-1;
endwhile
Postcondition={sum=1+2+...+n}
It is not necessary to develop this example. I just need to understand the procedure because I don't have a practical example. Thanks for your time.
Hoare logic's "while" rule must be applied here:
This is the only technique for proving the postcondition of a
whileloop in Hoare logic, so you must apply it. The conditionBand the loop bodySare given in the code, butPcan be any condition you choose so long as{P ∧ B} S {P}holds.This Hoare triple asserts that if
Pis true before an iteration of the loop then it will still be true afterwards, so such a conditionPis known as a loop invariant. To prove the postcondition of the loop you need to establish (1) thatPis true before the first iteration of the loop, and (2) thatPis preserved by the loop body.The necessary invariant for the loop in your example is
sum = n + (n-1) + ... + (cont+1), i.e. the sum of the numbers fromcont+1ton. In general, there is no systematic way to find the right loop invariant to use; you have to use your understanding of the algorithm, and your intuition/experience to come up with one yourself.This is sufficient to show that if the loop terminates then its postcondition will be satisfied; you also need to establish that the loop does terminate. The technique you should apply here is to find a loop variant; this is usually some integer quantity which (1) decreases on each iteration of the loop, and (2) causes the loop to terminate when the quantity reaches zero.
In your example,
contis a loop variant, because the loop decrementscont := cont-1, and the loop condition terminates the loop whencontreaches zero. In general, like finding a useful invariant, there is no systematic procedure which finds a variant in all cases, but you can start by looking at the loop condition to see which variable(s) determine when the loop terminates.