0

I don't know how to find a loop invariant. I'm not sure where to start. Can anyone find the loop invariant of the given program and explain your method please.

{n ≥ 0 ∧ i = 0}
while i < n − 1 loop
b[i] := a[i + 1];
i:=i + 1
end loop
{∀j.(0 ≤ j < n − 1 → b[j] = a[j + 1])}
the_martian
  • 632
  • 1
  • 9
  • 21

1 Answers1

0
  1. while i < n − 1 loop
  2. b[i] := a[i + 1];
  3. i := i + 1
  4. end loop

Invariant: Before step 2, 1 <= i + 1 < n and for all 0 <= j <= i - 1 is b[j] = a[j + 1].

The invariant is (trivially) true when i = 0 (there is no j satisfying 0 <= j <= i - 1). Moreover, if it is true for some i, it will remain true for i + 1, provided i + 1 < n (otherwise the loop is finished), because after 2 we also know that b[i] = a[i + 1].

Leandro Caniglia
  • 14,495
  • 4
  • 29
  • 51