-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixMultiplication.java
More file actions
79 lines (63 loc) · 2.02 KB
/
MatrixMultiplication.java
File metadata and controls
79 lines (63 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// WAP to perform matrix Multiplication 3x3
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r1,c1,r2,c2;
System.out.print("Enter number of rows and cols of matrix A: ");
r1 = sc.nextInt();
c1 = sc.nextInt();
System.out.print("Enter number of rows and cols of matrix B: ");
r2 = sc.nextInt();
c2 = sc.nextInt();
if(c1 != r2){
System.out.println("For matrix Multiplication columns of matrix A must equal to the rows of matrix B");
return;
}
int A[][] = new int[r1][c1];
int B[][] = new int[r2][c2];
int C[][] = new int[r1][c2];
System.out.println("Enter elements of Matrix A:");
for(int i=0;i<r1;i++){
for(int j=0;j<c1;j++){
A[i][j] = sc.nextInt();
}
}
System.out.println("Enter elements of Matrix B:");
for(int i=0;i<r2;i++){
for(int j=0;j<c2;j++){
B[i][j] = sc.nextInt();
}
}
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
C[i][j] = 0;
for(int k = 0; k < c1; k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
System.out.println("Matrix A: ");
for(int[] row : A){
for(int ele : row){
System.out.print(ele + " ");
}
System.out.println();
}
System.out.println("Matrix B: ");
for(int[] row : B){
for(int ele : row){
System.out.print(ele + " ");
}
System.out.println();
}
System.out.println("Resultant Matrix (A X B):");
for(int[] row : C){
for(int ele : row){
System.out.print(ele + " ");
}
System.out.println();
}
sc.close();
}
}