Given a matrix of custom size the task is to calculate and print sum of each column.
Example: Consider a matrix
| 1 | 4 | 7 |
| 3 | 2 | 8 |
| 5 | 6 | 9 |
Sum of column 1: 1+3+5 = 9.
Sum of column 2: 4+2+6 = 12.
Sum of column 3: 7+8+9 = 24.
The program should output only the sum with the column number.
Java
import java.util.*;
public class SumColumn
{
public static void main(String args[])
{
int row=0,col=0,sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
row=sc.nextInt();
System.out.print("Enter no.of columns: ");
col=sc.nextInt();
int ar[][]=new int[row][col];
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
for(int i=0;i<col;i++)
{
for(int j=0;j<row;j++)
{
sum=sum+ar[j][i];
}
System.out.println("Sum of Column "+(i+1)+": "+sum);
sum=0;
}
}
}Java