Skip to content

Commit 344c09a

Browse files
Add files via upload
1 parent 7fb7164 commit 344c09a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Addingmatrix.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.util.*;
2+
3+
class AddingMatrix {
4+
public static void main(String[] args) {
5+
Scanner sc = new Scanner(System.in);
6+
7+
System.out.println("Enter the number of rows for the first matrix:");
8+
int aRows = sc.nextInt();
9+
System.out.println("Enter the number of columns for the first matrix:");
10+
int aCols = sc.nextInt();
11+
int a[][] = new int[aRows][aCols];
12+
13+
System.out.println("Enter the elements for the first matrix:");
14+
for (int i = 0; i < aRows; i++) {
15+
for (int j = 0; j < aCols; j++) {
16+
a[i][j] = sc.nextInt();
17+
}
18+
}
19+
20+
System.out.println("Enter the number of rows for the second matrix:");
21+
int bRows = sc.nextInt();
22+
System.out.println("Enter the number of columns for the second matrix:");
23+
int bCols = sc.nextInt();
24+
int b[][] = new int[bRows][bCols];
25+
26+
System.out.println("Enter the elements for the second matrix:");
27+
for (int i = 0; i < bRows; i++) {
28+
for (int j = 0; j < bCols; j++) {
29+
b[i][j] = sc.nextInt();
30+
}
31+
}
32+
33+
if (aRows != bRows || aCols != bCols) {
34+
System.out.println("Matrices cannot be added. They have different dimensions.");
35+
} else {
36+
int result[][] = new int[aRows][aCols];
37+
for (int i = 0; i < aRows; i++) {
38+
for (int j = 0; j < aCols; j++) {
39+
result[i][j] = a[i][j] + b[i][j];
40+
}
41+
}
42+
43+
System.out.println("After adding the matrices:");
44+
for (int i = 0; i < aRows; i++) {
45+
for (int j = 0; j < aCols; j++) {
46+
System.out.print(result[i][j] + " ");
47+
}
48+
System.out.println();
49+
}
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)