Programming and Problem Solving with Java

(やまだぃちぅ) #1
12.2 P r o cessing Two-Dimensional Arrays | 587

Sum the Rows


Suppose we want to sum row number 3 (the fourth row) in the array and print the result. We
can do this easily with a forloop:


int total = 0;
for (int col = 0; col < data[3].length; col++)
total = total + data[3][col];
outFile.println("Row sum: "+ total);


This forloop runs through each column of data, while keeping the row index fixed at 3. Every
value in row 3 is added to total.
Now suppose we want to sum and print two rows—row 2 and row 3. We can use a nested
loop and make the row index be a variable:


for (int row = 2; row <= 3; row++)
{
int total = 0;
for (int col = 0; col < data[row].length; col++)
total = total + data[row][col];
outFile.println("Row sum: "+ total);
}


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 itera-
tion of the outer loop,rowis held at 2 and colgoes from 0 through data[2].length. Therefore,
the array is accessed in the following order:


data[2][0] [2][1] [2][2] [2][3] ... [2][29]


In the second iteration of the outer loop,rowis incremented to 3, and the array is accessed
as follows:


data[3][0] [3][1] [3][2] [3][3] ... [3][29]


We can generalize this row processing to run through every row of the array by having
the outer loop run from 0 through data.length-1. However, if we want to access only part of
the array (subarray processing), given variables declared as


int rowsFilled; // Data is in 0..rowsFilled – 1
int colsFilled; // Data is in 0..colsFilled – 1


then we write the code fragment as follows:


for (int row = 0; row < rowsFilled; row++)
{

Free download pdf