-4

I am very new to Algorithms and although i understand its very simple code im finding it difficult to find the loop invariant in the code below. Can someone please explicitly tell me what a good loop invariant for the code below is. Any help is much appreciated

int sumBetween (int x , int y){
    //pre-condition : x<=y
    //post : returns the sum x+(x+1)+(x+2)+.........+y
    int sum=0;
    for(int i=x; i!=y+1; i++) {
        sum+=i;
    }

I cant think of any loop invariant other than sum equalling all the integers from x to y but that is not true before the first iteration. Is there a loop invariant that covers the post-condition ?

Chris
  • 1
  • 1

1 Answers1

1

The loop invariant is that which does not vary from iteration to iteration.

In your case, that's the variable y.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142