1

I saw an example program which sets every value in an array to 0:

int a[n]; int i = 0;
while(i < n) {
    a[i] = 0;
    i++;
}

It said that part of the loop invariant was 0<=i<n. However, after the loop is finished terminating, i will equal n. Am i correct in saying that this is then not part of the loop invariant? If so, what should it be replaced with? The full invariant was For All j (0<= j < i --> a[i] = 0) & 0 <= i < n)

rohaldb
  • 589
  • 7
  • 24
  • The complete loop invariant is usually false after a loop. Sometimes achieving that state is the point of the loop. Sometimes, as here, a part of the loop invariant holds true also immediately after the loop, where that is the point. – Cheers and hth. - Alf Apr 08 '16 at 05:12

1 Answers1

0

The loop invariant must hold on loop entry and be preserved by every iteration, including the last iteration.

Therefore the loop invariant should be 0 <= i <= n

To support my claim, I offer as evidence your program translated into the automatically verified language Microsoft Dafny:

method Main(a:array<int>) requires a != null modifies a ensures forall j :: 0 <= j < a.Length ==> a[j] == 0 { var i:int := 0; while(i < a.Length) invariant 0 <= i <= a.Length invariant forall j :: (0 <= j < i ==> a[j] == 0) { a[i] := 0; i := i+1; } }

You can check that this program does indeed verify by running it in the online version of Dafny.

lexicalscope
  • 7,158
  • 6
  • 37
  • 57