0

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • I guess that it computes the sum of a number, like the factoriel but with the sum no? For the part of the loop invariant I have no idea – user2977595 Mar 01 '14 at 09:34

2 Answers2

2

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.

mathfac
  • 196
  • 1
  • 8
0

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.

Ali Adlavaran
  • 3,697
  • 2
  • 23
  • 47