Skip to content

Commit 9ac26f9

Browse files
committed
Add two matrices
1 parent 37a06fe commit 9ac26f9

File tree

2 files changed

+66
-31
lines changed

2 files changed

+66
-31
lines changed

InterviewPrograms/src/com/java/array/FindPairForZ.java

Lines changed: 0 additions & 27 deletions
This file was deleted.
Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
package com.java.matrix;
22

3+
/*
4+
* Add Two Matrix
5+
*
6+
* Addition is possible only when both A & B
7+
* matrices should have same dimensions, that is
8+
* both matrix should have same number of rows
9+
* and same number of columns.
10+
*
11+
* Then add the corresponding elements means
12+
* A[i][j] + B[i][j]
13+
*
14+
* Store the result in the new matrix called C
15+
*/
316
public class MatrixAddition {
417

518
public static void main(String[] args) {
@@ -9,26 +22,75 @@ public static void main(String[] args) {
922
{9,10,11,12},
1023
{13,14,15,16}
1124
};
25+
int row1 = 4, col1 = 3;
1226

1327
int matrixB[][] = {
1428
{5,10,15,20},
1529
{25,30,35,40},
1630
{45,50,55,60},
1731
{65,70,75,80}
1832
};
19-
int rows = 4;
20-
int columns = 4;
33+
int row2 = 4, col2 = 4;
34+
35+
if(row1 != row2 || col1 != col2){
36+
System.out.println("Addition is not possible");
37+
return;
38+
}
39+
40+
int rows = row1;
41+
int columns = col1;
2142

2243
int resultMatrix[][] = new int[rows][columns];
2344
for(int i=0;i<rows;i++)
2445
for(int j=0;j<columns;j++)
2546
resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
2647

48+
System.out.println("Matrix A is :: ");
49+
display(matrixA, rows, columns);
50+
51+
System.out.println("Matrix B is ::");
52+
display(matrixB, rows, columns);
53+
2754
System.out.println("Addition of two matrix is ::");
55+
display(resultMatrix, rows, columns);
56+
}
57+
58+
static void display(int matrix[][],int rows,int columns){
2859
for(int i=0;i<rows;i++){
2960
for(int j=0;j<columns;j++)
30-
System.out.print(resultMatrix[i][j]+" ");
61+
System.out.print(matrix[i][j]+" ");
3162
System.out.println();
32-
}
63+
}
3364
}
3465
}
66+
/*
67+
INPUT
68+
Matrix A is ::
69+
1 2 3 4
70+
5 6 7 8
71+
9 10 11 12
72+
13 14 15 16
73+
Matrix B is ::
74+
5 10 15 20
75+
25 30 35 40
76+
45 50 55 60
77+
65 70 75 80
78+
OUTPUT
79+
Addition of two matrix is ::
80+
6 12 18 24
81+
30 36 42 48
82+
54 60 66 72
83+
78 84 90 96
84+
85+
INPUT
86+
Matrix A is ::
87+
1 2 3 4
88+
5 6 7 8
89+
Matrix B is ::
90+
5 10 15
91+
20 25 30
92+
35 40 45
93+
OUTPUT
94+
Addition is not possible
95+
96+
*/

0 commit comments

Comments
 (0)