Java Reference
In-Depth Information
In the section, Processing Two-Dimensional Arrays, we described various algorithms to
process the elements of a two-dimensional array. Using those algorithms, we can write
methods that can be used in a variety of applications. In this section, we write some
of these methods. For simplicity, we assume that we are processing the entire two-
dimensional array.
The following method outputs the elements of a two-dimensional array, one row per
line:
public static void
printMatrix(
int
[][] matrix)
{
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();
}
}
Similarly, the following method outputs the sum of the elements of each row of a two-
dimensional array whose elements are of type
int
:
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];
System.out.println("The sum of the elements of row "
+ (row + 1) + " = " + sum);
}
}
The following method determines the largest element in each row:
public static void
largestInRows(
int
[][] matrix)
{
int
largest;
//The largest element in each row
for
(
int
row = 0; row < matrix.length; row++)
Search WWH ::
Custom Search