The following questions refer to the code shown below count
The following questions refer to the code shown below: count = n; sum = 0; while count 0 do sum = sum + count; count = count - 1; end (sum =1 + 2 + ... + n} What is the weakest precondition for this code and the given postcondition? Give an invariant that is strong enough to prove the partial correctness of the loop. Make your invariant as weak as possible. Give an invariant that is strong enough to prove the total correctness of the loop.
Solution
(a) The weakest precondition is that variables count and sum are of integer variables.
(b) We have to add the numbers from 1 to n. The loop invariant (count>=0 and count<=n) shows that as rquired we only consider the number from 0 to n in the loop.
(c) The invariant strong enough is that sum = (n+(n-1)...count) at any stage of the loop. At the end of loop count becomes 0, giving us the required value.
