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 (100 points) a. Write a program that reads

ID: 650029 • Letter: #

Question

***JAVA

Sum elements column by column (100 points)

a. Write a program that reads an 3 by 4 matrix and displays the sum of each column.

Here is the sample run:

Enter a 3 by4 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

b. Rewrite your program with a method that returns the sum of all the elements in a specified column(solumnIndex) in a matrix using the following header:

Public static double sumColumn (double[][] m, int columnIndex) { }

Explanation / Answer

public class SumElementsColumnByColumnClass {
public static void main(String[] args) {
double[][] m = createArray();

int i = 0;
double sumA = sumColumn(m, i);
double sumB = sumColumn(m, i);
double sumC = sumColumn(m, i);
double sumD = sumColumn(m, i);

System.out.println("Sum of the elements at column " + i + " is " + sumA);
System.out.println("Sum of the elements at column " + (i+1) + " is " + sumB);
System.out.println("Sum of the elements at column " + (i+2) + " is " + sumC);
System.out.println("Sum of the elements at column " + (i+3) + " is " + sumD);
}

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();

return m;
}

public static double sumColumn(double[][] m, int columnIndex){//this int 'columnIndex'
double total = 0.0;
for (int row = 0; row < m.length; row++) {
total += m[row][columnIndex]; //is used here
}
return total;
}
}