How to sum a row in a matrix

后端 未结 6 1860
情话喂你
情话喂你 2021-01-23 05:54

Write the method:

public int sumRow(int[][] matrix, int row)

that sums row row in the 2D array called matrix.

Given:

6条回答
  •  星月不相逢
    2021-01-23 06:26

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

提交回复
热议问题