int i, temp;
a is an array of integers [1...100]
i = 1;
while i < 100
if a[i] > a[i+1]
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
i = i+1
I'm having trouble understanding how to find loop invariants and writing a formal statement for them. So a loop invariant is just a condition that is true immediately before and after each iteration of a loop. It looks like the code is doing a swap: if the following element is greater in the array than the current one, switch places. I mean from the definition of a loop invariant, it really sounds like it's i < 100 because that must be true for the loop to run, but I don't really understand. Would greatly appreciate some clarification.
Your loop is controlled by the test
i < 100
. Within the body of the loop,i
is used in several places but is only assigned in one place. The assignment always happens, and for any value ofi
which permits entry to the loop the assignment will converge towards the terminating condition. Thus the loop is guaranteed to terminate.As for correctness of your program, that's a different issue. Depending on whether your arrays use zero-based or one-based indexing, the way you're using
i
for array accesses could be problematic. If it's zero-based, you never look at the first element and you'll step out of bounds witha[i+1]
on the last iteration.