1

I have a program, where I should find a loop invariant and then provide a proof.

      {x>=0 && y>=0} // precondition
res:=0;
i:=0;
while (i<y) do
res:=res+x;
i:=i+1;
od
      {res:=x*y} //postcondition

The only logical loop invariant for me is res<=x*y, which is straightforward from postcondition, but I dont think that it the best one to go on with. Maybe any other suggestions?

nlimits
  • 103
  • 1
  • 12

1 Answers1

1

Would this work?

{x>=0 && y>=0} // precondition
res:=0;
i:=0;
while (i<y) do
    {res=x*i} // invariant
    res:=res+x;
    i:=i+1;
    {res=x*i} // invariant
end
{res=x*y} //postcondition

By these conditions you should be able to show both that the program is partially correct (i.e. if the loop terminates, the answer is correct) and that it terminates. Although I suppose you need the precondition that y is an integer, too.

d125q
  • 1,666
  • 12
  • 18
  • Thanks, but why you mentioned it twice? I mean it is for sure that it should hold true both at the beginning and at the end. And, I logically got how to show that it is partially correct but what about fully? Can you give a hint on that? – nlimits Jul 19 '15 at 17:13
  • 1
    I mentioned it twice to make sure that the operations within the loop's body preserve the invariant ([... an invariant of a loop is a property that holds before (and after) each repetition](https://en.wikipedia.org/wiki/Loop_invariant)). As for total correctness, you have that total correctness is the same as partial correctness + the loop terminating. – d125q Jul 19 '15 at 20:22