Skip to content

Commit e92be42

Browse files
Add files via upload
1 parent 344c09a commit e92be42

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

MatrixMultiplication.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.*;
2+
3+
public class MatrixMultiplication {
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 (aCols != bRows) {
34+
System.out.println("Matrices cannot be multiplied. Invalid dimensions.");
35+
} else {
36+
int result[][] = new int[aRows][bCols];
37+
for (int i = 0; i < aRows; i++) {
38+
for (int j = 0; j < bCols; j++) {
39+
result[i][j] = 0;
40+
for (int k = 0; k < aCols; k++) {
41+
result[i][j] += a[i][k] * b[k][j];
42+
}
43+
}
44+
}
45+
46+
System.out.println("After multiplying the matrices:");
47+
for (int i = 0; i < aRows; i++) {
48+
for (int j = 0; j < bCols; j++) {
49+
System.out.print(result[i][j] + " ");
50+
}
51+
System.out.println();
52+
}
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)