In: Computer Science
Please do in java with code available for copy and with comments so I can follow along :)\
Develop a program that prints out the sum of each column of a two-dimensional array. The program defines method sumColumn() takes a two-dimensional array of integers and returns a single-dimensional array that stores the sum of columns of the passed array. The program main method prompts the user to enter a 3-by-4 array, prints out the array, and then calls method sumColumns(). Finally, it prints out the array retuned by method sumColumns(). Document your code, and organize and space the outputs properly as shown below. C++ students: instead of asking the user for input, you must read it from a file. See appendix for more information.
Sample run 1:
Enter a value: 9
Enter a value: 1
Enter a value: 2
Enter a value: 4
.
.
.
Enter a value: 3
The entered matrix:
9 1 2 4
2 2 8 0
3 3 3 3
Sum of column 0 is 14
Sum of column 1 is 6
Sum of column 2 is 13
Sum of column 3 is 7
import java.util.*;
public class Main
{
static int [] sumColumn(int arr[][])
{
int i,sum=0,j;
int []res=new int[4];
for(j=0;j<4;j++)//columns loops(loop through column)
{
sum=0;//initialize sum to 0 for every iterration
for(i=0;i<3;i++)//loop through rows
{
sum+=arr[i][j];//add columns elements for each row
}
res[j]=sum;//store the sum value in result array
}
return res;//return array
}
public static void main(String[] args) {
int [][]arr=new int[3][4];
int []result=new int[4];//resultant
array to store return array
int i,j;
Scanner s=new
Scanner(System.in);//Scanner class to read input
System.out.println("enter values
forn3 rows and 4 columns");
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
System.out.print("enter a
value:");//read the int values
arr[i][j]=s.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)//print the
values
{
System.out.print(arr[i][j]+"
");
}
System.out.println();
}
result=sumColumn(arr);//call
function and store in result array
for(i=0;i<4;i++)
{
System.out.println("Sum of column
"+i+" is "+result[i]);
}
}
}
//For c++ users you asked to input from file but in java you didn't
mention if you want to input from file let me know I will update
code