/* PROOF OF CORRECTNESS: SUM(N, X[]): compute the summation of N integers in array X Trace: sum(5, x[]) i x[i] s SUM(i) ----------------------- 0 0 0 0 // i=0 implies that zero numbers have been summed 1 1 0 0 // i=1 implies that one number has been summed, i.e. x[0]=0 2 2 1 1 3 3 3 3 4 4 6 6 The restriction on the loop index: i <= n along with the EXIT ( In the following proof, we use SUM(n) to represent the summation of the first n integers in the array: x[0] + ... + x[n-1] The partial computation of the INVARIANT: s = SUM(i) says that s accumulates the first i integers in x: x[0] + x[1] + ... + x[i-1]. The restriction on the loop index in the INVARIANT: i <= n along with the EXIT CONDITION (i >= n) prove what our eyes already knew: i = n after the loop. This proves the POST-CONDITION: s = SUM(i) and i = n implies s = SUM(n). */ #include int sum(int n, int x[]) { int i, s; // PRE: n >= 0 i = 0; // n >= 0 and i = 0 s = 0; // n >= 0 and i = 0 and s = 0 // INVARIANT: s = SUM(i) and i <= n while (i < n) { // s = SUM(i) and i < n s = s + x[i]; // s = SUM(i+1) and i < n i = i + 1; // s = SUM(i) and i <= n } // end while // INVARIANT: s = SUM(i) and i <= n and EXIT: i >= n // s = SUM(i) and i = n // POST: s = SUM(n): x[0] + ... + x[n-1] return s; } #define n 5 int main() { int i; int x[n]; printf("sum( "); for (i=0; i