0

I don't quite understand how to determine the loop invariant. I understand that its something that is true before a loop, after a loop, and during each loops iteration, but thats about it. Here is an example problem I'm working on, how would you find the loop invariant of this?

i, temp : integer; 
values : array[1..100] of integer; 

x := 1; 

while x < 100 loop 

if values[x] > values[x+1] then begin 

temp := values[x]; 

 values[x] := values[x+1]; 

 values[x+1] := temp; 

 end if; 

 x := x + 1; 

end loop; 
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96

3 Answers3

0

In simple words, a loop invariant is some predicate (condition) that holds good (true) for every iteration of the loop.

In your case, the loop invariant will be:

x >= 1 && x < 100

Given the termination condition, the above expression will always remain true throughout the loop. If it becomes false, the loop ends.

CinCout
  • 9,486
  • 12
  • 49
  • 67
0

1 <= x <= 100 is the loop invariant. Always true before and after each loop repitition.

A loop invariant should be true on entry into a loop and is guaranteed to remain true after every iteration of the loop. This means that on exit from the loop both the loop invariant and the loop termination condition can be guaranteed.

See the Floyd-Hoare logic section with simple x<10 loop example: http://en.wikipedia.org/wiki/Loop_invariant

xagyg
  • 9,562
  • 2
  • 32
  • 29
0

You definition of loop invariant is not exactly correct. Essentially it should be true only before and after each loop repetition. WikiPedia have nice definition.

The invariant of this loop would be: the values[x] and values[x + 1] are maybe not sorted or x is the last index it's true before and after each loop iteration. And it's still true right after loop combined with false for loop condition:

i, temp : integer; 
values : array[1..100] of integer; 

x := 1; 

while x < 100 loop 
    // the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
    if values[x] > values[x+1] then begin 
        temp := values[x]; 
        values[x] := values[x+1]; 
        values[x+1] := temp; 
    end if; 
    x := x + 1; 
    // the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
end loop; 

// the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
// and x >= 100 - true

naturally, loop invariant should be related to loop body and the task it performs. The loop invariant insures that on each step of the loop you have same conditions for the loop body to perform.

Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96