Sum Of Each Row And Each Column Of A Matrix

Sum Of Each Row And Each Column Of A Matrix


Write a program to print the sum of each row and each column of a m x n matrix.

import java.io.*; class SumOfEachRowCol { public static void main(String ar[])throws Exception { BufferedReader ob=new BufferedReader( new InputStreamReader(System.in)); int i,j,srow,scol, m, n; System.out.println("Enter the number of rows and columns of the matrix : "); m=Integer.parseInt(ob.readLine()); n=Integer.parseInt(ob.readLine()); int a[][]=new int[m][n]; System.out.println("\nEnter "+(m*n)+" elements : "); for(i=0;i< m;i++) { for(j=0;j< n;j++) { a[i][j]=Integer.parseInt(ob.readLine()); } } //sum of each row for(i=0;i< m;i++) { srow=0; for(j=0;j< n;j++) { srow+=a[i][j]; } System.out.println("\nSum of row "+(i+1)+" : "+ srow); } //sum of each column for(i=0;i< n;i++) { scol=0; for(j=0;j< m;j++) { scol+=a[j][i]; } System.out.println("\nSum of column "+(i+1)+" : "+ scol); } } }

Have something to say? Log in to comment on this post.

0 comments