Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA! (Sum elements column by column) Write a method that returns the sum of all

ID: 3693571 • Letter: J

Question

JAVA!

(Sum elements column by column) Write a method that returns the sum of all the elements in a specified column in a matrix using the following header: public static double sumColumn(double[][] m, int columnlndex) Write a test program that reads a 3-by-4 matrix and displays the sum of each column. Here is a sample run: Enter a 3-by-4 matrix row by row: 1.5 2 3 4 5.5 6 7 8 9.5 1 3 1 sum of the elements at column 0 is 16.5 sum of the elements at column 1 is 9.0 sum of the elements at column 2 is 13.0 sum of the elements at column 3 is 13.0

Explanation / Answer

import java.util.Scanner;

/**
* @author
*
*/
public class SumColumn {

   /**
   * method to calculate the sum of elements at the given column
   *
   * @param m
   * @param columnIndex
   * @return
   */
   public static double sumColumn(double[][] m, int columnIndex) {

       double sum = 0.0;
       for (int i = 0; i < m.length; i++) {
           sum += m[i][columnIndex];
       }
       return sum;

   }

   /**
   * @param args
   */
   public static void main(String[] args) {

       Scanner scanner = null;
       try {

           scanner = new Scanner(System.in);
           double m[][] = new double[3][4];
           System.out.println("Enter a 3-by-4 matrix row by row");
           for (int i = 0; i < m.length; i++) {
               for (int j = 0; j < m[i].length; j++) {
                   m[i][j] = scanner.nextDouble();
               }

           }
           for (int i = 0; i < m[0].length; i++) {
               System.out.println("Sum of the elements at column " + i
                       + " is " + sumColumn(m, i));
           }
       } catch (Exception e) {
           // TODO: handle exception
       } finally {

           scanner.close();
       }

   }
}

OUTPUT:

Enter a 3-by-4 matrix row by row
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0