How to sum 2D array (matrix) cols in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int[][] matrix = {{31, 22, 33}, 
                          {42, 85, 987}};
        int[] cols_sum = {0, 0, 0};
         
        sum_matrix_cols(matrix, cols_sum);
         
        for (int i = 0; i < 3; i++) 
            System.out.println(cols_sum[i]);
    }
    public static void sum_matrix_cols(int[][] matrix, int[] cols_sum) {
        int rows = matrix.length;
        int cols = matrix[0].length;
           
         for (int j = 0; j < cols; j++) {
                for (int i = 0; i < rows; i++)
                    cols_sum[j] += matrix[i][j];
        }
    }
}
    
/*
                   
run:
      
73
107
1020
          
*/

 



answered Apr 18, 2018 by avibootz

Related questions

2 answers 434 views
1 answer 216 views
216 views asked Apr 18, 2018 by avibootz
1 answer 178 views
1 answer 177 views
177 views asked Apr 18, 2018 by avibootz
2 answers 239 views
1 answer 129 views
129 views asked Apr 13, 2018 by avibootz
1 answer 218 views
218 views asked Apr 13, 2018 by avibootz
...