How to sum a row in a matrix

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

    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

提交回复
热议问题