Given the following code fragment, where x is a number.
{ y >= 0 }
z = 0
n = y
while (n > 0) begin
z = z + x
n = n – 1
end
What does it compute? Prove it, showing how you derive the loop invariant.
How can I do that please?
Given the following code fragment, where x is a number.
{ y >= 0 }
z = 0
n = y
while (n > 0) begin
z = z + x
n = n – 1
end
What does it compute? Prove it, showing how you derive the loop invariant.
How can I do that please?
This example is known like most correct program, because it is proved in every software verification course. Here is listing of the program with invariants on every step:
{ y >= 0 }
z = 0 // invariant: z = 0
n = y // invariant: n = y and z = 0
while (n > 0) begin // loop invariant: y * x - n * x = z
z = z + x
n = n – 1
end
// Final invariant: n = 0 and y * x = z
All theoretical details for this example are provided in my paper page 118.
For given X
and Y
it computes X * Y
.
at the beginning, value of the Z
is zero, and the N = Y
(loop's variable which will countdown in our loop).
the loop executes Y
times and in every time that it executes, it accumulates the X
to the Z
.
finally, when the N
reached to 0 the loop will terminate, then the value of Z
should be X * Y
.