[prev] 7 [next]

Exercise: Testing a function

Consider the notion that an array int A[N] is ordered:

ordered(A[N]):  forall i:1..N-1,  A[i] >= A[i-1]

and some code to implement this test

ordered = 1; // assume that it *is* ordered
for (i = 1; i < N; i++) {
    if (A[i] >= A[i-1])
        /* ok ... still ordered */;
    else
        ordered = 0; // found counter-example
}
// ordered is set appropriately

Put this code in a function and write a driver to test it.

Print "Yes" if ordered, or print "No" otherwise.