Java Reference
In-Depth Information
INPUT
The following for loop inputs data into row number 4 (the fifth row) of matrix :
int row = 4;
for ( int col = 0; col < matrix[row].length; col++)
matrix[row][col] = console.nextInt();
As before, by putting the row number in a loop, you can input data into each element of
matrix . The following for loop inputs data into each element of matrix :
for ( int row = 0; row < matrix.length; row++)
for ( int col = 0; col < matrix[row].length; col++)
matrix[row][col] = console.nextInt();
SUM BY ROW
The following for loop finds the sum of the elements of row number 4 of matrix ; that
is, it adds the elements of row number 4 :
sum = 0;
int row = 4;
for ( int col = 0; col < matrix[row].length; col++)
sum = sum + matrix[row][col];
Once again, by putting the row number in a loop, you can find the sum of each row
separately. The Java code to find the sum of each individual row follows:
//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);
}
SUM BY COLUMN
As in the case of sum by row, the following nested for loop finds the sum of the elements of each
individual column. (Notice that matrix[0].length gives the number of columns in each row.)
//Sum of each individual column
for ( int col = 0; col < matrix[0].length; col++)
{
sum = 0;
for ( int row = 0; row < matrix.length; row++)
sum = sum + matrix[row][col];
Search WWH ::




Custom Search