Write the method:
public int sumRow(int[][] matrix, int row)
that sums row row
in the 2D array called matrix.
Given:
You're currently trying to sum all of the elements in the 2D array when you were asked to sum a specific row within the 2D array. In this case, you only need one for loop to traverse a single row like you would traverse a single array. The loop would start at the first element, matrix[row][0]
and run until the last element, matrix[row][matrix[row].length - 1]
since matrix[row].length
is the number of columns/elements in that specific row of the matrix. Therefore, matrix[row].length - 1
would be the index of the last element in matrix[row]
. Here's what it should look like,
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
for(int i = 0; i < matrix[row].length; i++)
{
sum += matrix[row][i];
}
return sum;
}
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
int colSize = matrix[row].length;
for(int j = 0; j < colSize; j++){
sum += matrix[row][j];
}
return sum;
}
HINT
Length of row:
int row = matrix.length;
Length of column :
int col = matrix[0].length;
there is a problem with your second for
loop's condition , matrix.length
is the length of first dimension , for the second dimension it looks like matrix[i].length
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
sum = sum + matrix[i][j];
}
}
i prefer to use sum+=matrix[i][j]
instead of sum = sum + matrix[i][j]
calculating for one row :
for(int j = 0; j < matrix[row].length; j++){
sum = sum + matrix[row][j];
}
just note that row's range is from 0
to matrix.length-1
With Java Streams can be done very elegantly:
public static int sumRow2(int[][] matrix, int row) {
return Arrays.stream(matrix[row]).sum();
}
In the internal loop, modify the condition to:
for(int j = 0; j < matrix[i].length; j++)
and then switch i
and j
in the sum
You need to reference the second dimension of the array for j.
//ex: first dimension is matrix.length
//second dimension is matrix[any index in the first dimension].length
//and this cycle would continue with more and more [num] on the end
public int sumRow(int[][] matrix, int row)
{
int sum = 0;
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix**[0]**.length; j++)
{
sum = sum + matrix[j][i];
}
}
return sum;
}