1
+ /*
2
+ * PROGRAM : To find the sum of each row and each column of a matrix. Print the results along with input matrix.
3
+ * FILE : SumOfRowCol.java
4
+ * CREATED BY : Santosh Hembram
5
+ * DATE : 12-10-20
6
+ */
7
+ import java .util .*;
8
+ class SumOfRowCol {
9
+ public static void sumMatrix (int mat [][]) {
10
+
11
+ int r =1 ,c =1 ;
12
+ for (int i =0 ; i <mat .length ; i ++) {
13
+ int sum =0 ;
14
+
15
+ for (int j =0 ; j <mat [0 ].length ; j ++) {
16
+
17
+ sum = sum + mat [i ][j ];
18
+
19
+ }
20
+ System .out .println ("Sum of " +r +" row: " +sum );
21
+ r ++;
22
+ }
23
+ System .out .println ();
24
+ for (int i =0 ; i <mat [0 ].length ; i ++) {
25
+ int colSum =0 ;
26
+ for (int j =0 ; j <mat .length ; j ++) {
27
+ colSum = colSum + mat [j ][i ];
28
+
29
+ }
30
+ System .out .println ("Sum of " +c +" column: " +colSum );
31
+ c ++;
32
+
33
+ }
34
+ }
35
+
36
+ public static void main (String [] args ) {
37
+ Scanner sc = new Scanner (System .in );
38
+ System .out .print ("Enter the row size: " );
39
+ int r = sc .nextInt ();
40
+ System .out .print ("Enter the coloumn size: " );
41
+ int c = sc .nextInt ();
42
+ int mat [][] = new int [r ][c ];
43
+
44
+ System .out .println ("---------- Enter the elements of the matrix --------------" );
45
+ for (int i =0 ; i <r ; i ++) {
46
+ for (int j =0 ; j <c ; j ++) {
47
+
48
+ System .out .print ("Enter the elements for row " +i +" coloumn " +j +": " );
49
+ mat [i ][j ] = sc .nextInt ();
50
+ }
51
+ }
52
+ System .out .println ("---------- Displaying the matrix --------------" );
53
+ for (int i =0 ; i <r ; i ++) {
54
+ for (int j =0 ; j <c ; j ++) {
55
+
56
+ System .out .print (mat [i ][j ]+" " );
57
+
58
+ }
59
+ System .out .println ();
60
+ }
61
+ SumOfRowCol obj = new SumOfRowCol ();
62
+ obj .sumMatrix (mat );
63
+ }
64
+ }
0 commit comments