12.2 P r o cessing Two-Dimensional Arrays | 589
data
[ 0 ]
[ 0 ]
[ 1 ]
[ 2 ]
[rowsFilled– 1 ]
[data.length– 1 ]
[ 1 ][ 2 ]
[colsFilled– 1 ] [data[i].length– 6 ]
Figure 12.5 Subarray Processing by Column.
In this case, the outer loop controls the column, and the inner loop controls the row. All the
components in the first column are accessed and summed before the outer loop index
changes and the components in the second column are accessed. Figure 12.5 illustrates sub-
array processing by column.
Initialize the Array
Instantiating an array with initializer lists is impractical if the array is large. For a 100-row
by 100-column array, you don’t want to list 10,000 values. If the values are all different, you
should store them into a file and input them into the array at run time. If the values are all
the same, the usual approach employs nested forloops and an assignment statement. Here
is a general-purpose code segment that sets every item in the array to 1:
for (int row = 0; row < data.length; row++)
for (int col = 0; col < data[row].length; col++)
data[row][col] = –1;
In this case, we initialized the array a row at a time, but we could just as easily have run
through each column instead. The order doesn’t matter as long as we access every element.
Almost all processing of data stored in a two-dimensional array involves either pro-
cessing by row or processing by column. The looping patterns for row processing and column
processing are so useful that we summarize them next. To make them more general, we use
minRowfor the first row number and minColfor the first column number. Remember that row