Java: Sum elements column by column
package chapter8_8_1; import java.util.Scanner; /** * * @author Siavash Bakhshi */ public class Chapter8_8_1 { /** * @param args the command line arguments */ public static void main(String[] args) { double[][] m = createArray(); // Get an array double sum = 0.0; // Create a Scanner Scanner input = new Scanner(System.in); for (int column = 0; column < m[0].length; column++){ sum = sumColumn(m, column); System.out.println("Sum of the elements at column " + (column+1) + " is " + sum); } } public static double[][] createArray(){ Scanner input = new Scanner(System.in); double[][] m = new double[3][4]; System.out.println("Enter a " + m.length + "-by-" + m[0].length + " matrix row by row: "); for (int i = 0; i < m.length; i++){ for (int j = 0; j < m[0].length; j++){ m[i][j] = input.nextDouble(); } }//input.close(); return m; } public static double sumColumn(double[][] m, int columnIndex) { double total = 0.0; for (int row = 0; row < m.length; row++) { total += m[row][columnIndex]; } return total; } }Java: Sum elements column by column (901 downloads )