
CSCE 330 Fall 2007
Quiz 7
Assigned Thursday, 07-09-13
Give a loop invariant for this program fragment :
x := 2;
i := 1;
(*What is the precondition here?*)
while (i <= n) do
begin
x := x*x;
i := i+1
end
with precondition n≥1 and postcondition x= 22n.
Answer: x= 22i−1
∧i≤n+ 1.
Also answer the following questions.
1. What is the precondition before the loop? Answer: x= 2 ∧i= 1∧n≥1
2. Your invariant should consist of the conjuction of two formulas. One of
them should be very similar to the condition of the while loop. Explain
why that formula is needed. Answer: To insure that i=n+ 1 (rather
than just i > n) when the loop is exited.
3. Show that the precondition at the line with asterisks implies the invariant.
Answer: In short: (1) Since i= 1 and x= 2, then x= 22i−1. (2) Since
i= 1 and n≥1, then i≤n+ 1.
4. Show that the invariant together with the negation of the loop implies the
postcondition. Answer: In short: (1) Since i≤n+ 1 and i > n then
i=n+ 1. (2) Since x= 22i−1and i=n+ 1, then x= 22n.
5. Let xbe the value of the variable xbefore executing the body of the loop
and x’ be the value of the variable xafter executing the body of the loop.
Write an equation that relates xand x’.Answer: x′=x∗x.
6. Let ibe the value of the variable ibefore executing the body of the loop
and i’ be the value of the variable iafter executing the body of the loop.
Write an equation that relates iand i’.Answer: i′=i+ 1.
1