(Sum elements column by column) Write a method that returns the sum of all the e
ID: 3767745 • Letter: #
Question
(Sum elements column by column)
Write a method that returns the sum of all the elements in a specified column of 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
Explanation / Answer
class add_column
{
public static double sumColumn(double[][] m, int columnIndex)
{
int i,j;
double c=0;
for(j=0;j<4;j++)
{
c=c+m[columnIndex][j];
}
return c;
}
public static void main(String args[])
{
double m[][] = {{1.5, 2, 3, 4}, {5.5, 6, 7, 8},{9.5, 1, 3, 1}};
int i;
double r;
for(i=0;i<3;i++)
{
r=sumColumn(m,i);
System.out.println("Sum os the elemnts at column "+i +" is "+r);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.