Java Reference
In-Depth Information
matrix
[0] [1] [2] [3] [4] [5]
[0]
[1]
[2]
[3]
[4]
[5]
[6]
FIGURE 9-21
Two-dimensional array
matrix
For the two-dimensional array
matrix
, the value of
matrix.length
is
7
, which
is the same as the value of the named constant
ROWS
. Also, the values of
matrix[0].length
,
matrix[1].length
,...,
matrix[6].length
give
the number of columns in row 0, row 1, . . ., row 6, respectively. Notice that the
number of columns in each row is 6.
Because all the elements of a two-dimensional array are of the same type, the elements of
any row or column are of the same type. This means that in a two-dimensional array, the
elements of each row and each column can be processed as a one-dimensional array.
Therefore, when processing a particular row or column of a two-dimensional array, we use
algorithms similar to those that process one-dimensional arrays. We explain this concept
further with the help of the two-dimensional array
matrix
, as declared previously.
Suppose that we want to process row number
5
of
matrix
(the
sixth
row of
matrix
).
The elements of row number
5
of
matrix
are:
matrix[5][0], matrix[5][1], matrix[5][2], matrix[5][3], matrix[5][4],
matrix[5][5]
In these elements, the first index (the row position) is fixed at
5
. The second index (the
column position) ranges from
0
to
5
. Therefore, we can use the following
for
loop to
process row number
5
:
for
(
int
col = 0; col < matrix[5].length; col++)
//process matrix[5][col]
This
for
loop is equivalent to the following
for
loop:
int
row = 5;
for
(
int
col = 0; col < matrix[row].length; col++)
//process matrix[row][col]
Search WWH ::
Custom Search