Loop invariants: S is a statement, known loop
While C do
E
When this loop satisfies the following conditions: The statement S and C are true before any loops begin, and S is still true after the loop has ended, then S is the loop invariant
Cyclic invariants theorem: Guard condition G known as a cyclic and cyclic condition. The Life I (n) is a cyclic invariant. If the following four conditions are true, then this loop is the correct one
1) Basic property:the pre-condition implise I (0)
2) Induction property:for all ints k = 0, if guard and I (k) was true before the iteration, then I (k+1) was true after.
3) Eventual falsity of the Guard:after a finite number of iterations, G becomes false;
4) Correctness of Postconditons:if N is the first place where G is false, and I (N) are true, then post-condition holds.
Where guard condition G refers to the check of the cyclic variable before the loop, for example: I <= n in while (I < n)
For example, the maximum value in the array
Max (A[1],... A[n])
m = a[1]
i = 1
while (i <= N) does
If a[i] > m Then
m = A[i]
End If
i = i + 1
End While
return m
The prior condition of the loop is the first element of the array m = a[1] and i = 1. The posterior condition of the loop is that M is the largest element in array a. So now the loop invariants are I (i): M is the maximum value of the first I element in array a. The guard condition condition G is I <=n.
The correctness of the loop is proved by the derivation on I. First, note that n is a fixed integer, and that the initial value of I is smaller than N, and each time the loop n increases, at some point I <=n false. This always happens after the n-1 cycle.
Now to prove the loop invariants. First, I (1) is true, because a[1] = m, so there is only one element in the array, so at this point A[1] is definitely the largest. In order to derive, we assume that M is a[1] ... A[i], this hypothesis is I (i), we have to prove that after a cycle, I (i+1) will be set up. Consider two cases, 1) a[i+1]>m, in which case the a[i+1] is larger than the previous element in a, through transitivity, M=a[i+1] is also a[1] ... The largest element in a[i+1].
2) A[i+1]<m, at this point, the value of M is not changed.