|
|
|
|
|
|
|
Suppose we want to sum row number 3 (the fourth row) in array table and print the result. We can do this easily with a For loop: |
|
|
|
|
|
|
|
|
total = 0;
for (col = 0; col < NUM_COLS; col++)
// Invariant (prior to test):
// total == table[3][0] + + table[3][col-1]
// && 0 <= col <= NUM_COLS
total = total + table[3][col];
cout << Row sum: << total << endl; |
|
|
|
|
|
|
|
|
This For loop runs through each column of table, while keeping the row index equal to 3. Every value in row 3 is added to total. Suppose we wanted to sum and print two rowsrow 2 and row 3. We could add a duplicate of the preceding code fragment, but with the index set to 2: |
|
|
|
|
|
|
|
|
// Sum row 2 and print the sum
total = 0;
for (col = 0; col < NUM_COLS; col++)
// Invariant (prior to test):
// total == table[2][0] + + table[2][col-1]
// && 0 <= col <= NUM_COLS
total = total + table[2][col];
cout << Row sum: << total << endl;
// Sum row 3 and print the sum
total = 0;
for (col = 0; col < NUM_COLS; col++)
// Invariant (prior to test):
// total == table[3][0] + + table[3][col-1]
// && 0 <= col <= NUM_COLS
total = total + table[3][col];
cout << Row sum: << total << endl; |
|
|
|
|
|
|
|
|
or we could use a nested loop and make the row index a variable: |
|
|
|
|
|