Java Programming Write your own source code with comments Su
Java Programming. Write your own source code with comments.
(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 columnIndex) 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
Solution
import java.util.*;
public class HelloWorld{
//method to calculate sum of the column of matrix
public static double sumColumn(double[][] m, int columnIndex) {
double sum=0.0;//variable to store sum
/* run the loop till the maximum row */
for(int i=0;i<3;i++)
sum=sum+m[i][columnIndex]; /* calculating sum */
return sum; /* returning final sum value for each column */
}
/* test program */
public static void main(String []args){
Scanner input=new Scanner(System.in);/* object to take input from user 8/
double[][] m=new double[3][4]; /* declaring matrix */
System.out.println(\" Enter a 3-by-4 matrix row by row:\");
/* taking input from user */
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
m[i][j]=input.nextDouble();
}
/* calling sumColumn method for each column */
for(int i=0;i<4;i++)
System.out.println(\"Sum of the elements at column \"+i+\" is \"+sumColumn(m,i));
}
}
/***********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
*********OUTPUT***************/
/* Note: Please ask in case of any doubt,Thanks */
