Java Reference
In-Depth Information
Similarly, suppose that we want to process column number 2 (the third column) of
matrix . The elements of this column are:
matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2], matrix[4][2],
matrix[5][2], matrix[6][2]
Here, the second index (the column position) is fixed at 2 . The first index (the row
position) ranges from 0 to 6 . In this case, we use the following for loop to process
column 2 of matrix :
for ( int row = 0; row < matrix.length; row++)
//process matrix[row][2]
This for loop is equivalent to the following for loop:
int col = 2;
for ( int row = 0; row < matrix.length; row++)
//process matrix[row][col]
Next, we discuss some specific algorithms for processing two-dimensional arrays.
INITIALIZATION
Suppose that you want to initialize the elements of row number 4 (the fifth row) to
10 . As explained earlier, the following for loop initializes the elements of row number
4 to 10 :
int row = 4;
for ( int col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;
9
If you want to initialize the elements of the entire matrix to 10 , you can also put the first
index (the row position) in a loop. By using the following nested for loops, you can
initialize each element of matrix to 10 :
for ( int row = 0; row < matrix.length; row++)
for ( int col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;
PRINT
By using a nested for loop, you can output the elements of matrix . The following
nested for loops print the elements of matrix , one row per line:
for ( int row = 0; row < matrix.length; row++)
{
for ( int col = 0; col < matrix[row].length; col++)
System.out.printf("%7d", matrix[row][col]);
System.out.println();
}
Search WWH ::




Custom Search