Java Reference
In-Depth Information
System.out.println("The sum of the elements of column "
+ (col + 1) + " = " + sum);
}
(Note that the preceding code to find the sum of the elements of each column assumes
that the number of columns in each row is the same. In other words, the two-
dimensional array is not ragged.)
LARGEST ELEMENT IN EACH ROW AND EACH COLUMN
As stated earlier, another possible operation on a two-dimensional array is finding the largest
element in each row and each column. Next, we give the Java code to perform this operation.
The following for loop determines the largest element in row number 4 :
int row = 4;
largest = matrix[row][0]; //assume that the first element of the
//row is the largest
for ( int col = 1; col < matrix[row].length; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
The following Java code determines the largest element in each row and each column:
//The largest element of each row
for ( int row = 0; row < matrix.length; row++)
{
largest = matrix[row][0]; //assume that the first element
//of the row is the largest
for ( int col = 1; col < matrix[row].length; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
9
System.out.println("The largest element of row "
+ (row + 1) + " = " + largest);
}
//The largest element of each column
for ( int col = 0; col < matrix[0].length; col++)
{
largest = matrix[0][col]; //assume that the first element
//of the column is the largest
for ( int row = 1; row < matrix.length; row++)
if (largest < matrix[row][col])
largest = matrix[row][col];
System.out.println("The largest element of col "
+ (col + 1) + " = " + largest);
}
Passing Two-Dimensional Arrays as Parameters to Methods
Just like one-dimensional arrays, references to two-dimensional arrays can be passed as
parameters to a method.
 
Search WWH ::




Custom Search