Java Reference
In-Depth Information
{
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];
System.out.println("The largest element of row "
+ (row + 1) + " = " + largest);
}
}
In a similar fashion, you can write methods to find the sum of the elements of each
column, read data into a two-dimensional array, find the largest and/or smallest element
in each row or each column, and so on.
As in the case of one-dimensional arrays, to conveniently use the methods to process data
in a two-dimensional array, we put the definitions of the methods printArray , sumRows ,
largestInRows , and other such methods in the class TwoDimArraysMethods . The
definition of this class is:
// This class contains methods to process elements in two-
// dimensional arrays.
public class TwoDimArraysMethods
{
public static void printMatrix( int [][] matrix)
{
9
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();
}
} //end printMatrix
public static void sumRows( int [][] matrix)
{
int sum;
//sum of each individual row
for ( int row = 0; row < matrix.length; row++)
{
sum = 0;
for ( int col = 0; col < matrix[row].length; col++)
sum = sum + matrix[row][col];
Search WWH ::




Custom Search