# Finding a good loop invariant

I want to prove that the following program is correct. The code takes an array i of length N and a number x. At the end, the value of found should be true if the array contains x and false otherwise.

found := false;
i := 0 ;
while i < N do {
found := found || (a[i]=x);
i:=i+1
}


The given preconditions are that N >= 0 and that the array is sorted in ascending order (however, I don't know how the fact that it is sorted can help).

As postcondition, I think the following would suffice: the value of found equals the value of the predicate “there exists an i in the range [0, N) such that a[i] == x

However, I am stuck at this point and don't know how to continue. I cannot think of any loop invariant that has any relation to the postcondition. What would you suggest as a loop invariant?

You have an intended postcondition for a loop, and you're looking for an interesting invariant. In this scenario, try taking the intended postcondition, and replacing the total number of iterations (here N) by the number of iterations so far (here i). There's no guarantee that this is an invariant: that's only the case if the way the postcondition is somehow related to the structure of the loop. But if it is an invariant, it's definitely interesting, because it lets you prove the postcondition.
So we're interested in the following property: “the value of found equals the value of the predicate there exists a $k$ in the range $[0, i)$ such that $a[k] = x$”. Note that I use a name other than i for the existential variable, since i is now used in the context. The quantifier pile-up is:
for any value of N set before calling this snippet,
for any value of the variable i,
there exists an index $k$ such that …
Intuitively, this property states that found reflects whether the element is in the array up to the point that has been traversed. At the end of the loop that traverses the whole array, found reflects whether the element is in the whole array.