How to sum a row in a matrix

后端 未结 6 1859
情话喂你
情话喂你 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:45

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

提交回复
热议问题