< previous page page_715 next page >

Page 715
for (row = 2; row < 4; row++)
{
        // Invariant (prior to test):
        //     Rows 2 through row1 have been summed and printed
        // && 2 <= row <= 4

    total = 0;
    for (col = 0; col < NUM_COLS; col++)

            // Invariant (prior to test):
            //     total == table[row][0] +  + table[row][col-1]
            // && 0 <= col <= NUM_COLS

        total = total + table[row][col];
    cout << Row sum:  << total << endl;
}
The second approach is shorter, but its real advantage is that we can easily modify it to process any range of rows.
The outer loop controls the rows, and the inner loop controls the columns. For each value of row, every column is processed; then the outer loop moves to the next row. In the first iteration of the outer loop, row is held at 2 and col goes from 0 through NUM_COLS-1. Therefore, the array is accessed in the following order:
table[2][0]  [2][1]  [2][2]  [2][3]    [2][NUM_COLS-1]
In the second iteration of the outer loop, row is incremented to 3, and the array is accessed as follows:
table[3][0]  [3][1]  [3][2]  [3][3]    [3][NUM_COLS-1]
We can generalize this row processing to run through every row of the table by having the outer loop run from 0 through NUM_ROWS-1. However, if we want to access only part of the array (subarray processing), we write the code fragment as follows:
for (row = 0; row < rowLength; row++)
{
        // Invariant (prior to test):
        //     Rows 0 through row1 have been summed and printed
        //  && 0 <= row <= rowLength

 
< previous page page_715 next page >