Java Array multidimensional Arrays sum elements by column

Question

We would like to sum elements by column.

For each column, use a variable named total to store its sum.

Add each element in the column to total using a loop.


import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    int[][] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(matrix));
    //your code here
  }/*from ww  w .ja  va2  s . co  m*/
}


import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    int[][] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(matrix));
    for (int column = 0; column < matrix[0].length; column++) {
      int total = 0;
      for (int row = 0; row < matrix.length; row++)
        total += matrix[row][column];
      System.out.println("Sum for column " + column + " is " + total);
    }
  }
}



PreviousNext

Related