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;
}