Skip to content

Commit f45c3db

Browse files
authored
Merge pull request #44 from nancy0119/issue#14
Added the code of matrix multiplication
2 parents ef6abe3 + ec2b793 commit f45c3db

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

matrix Multiplication.java

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
MatrixMultiplication code helps in taking input as 2 matrices of any order and prints their product.
3+
*/
4+
5+
import java.io.*;
6+
import java.util.*;
7+
8+
public class matrixMultiplication{
9+
10+
public static void main(String[] args) throws Exception {
11+
Scanner s = new Scanner(System.in);
12+
// Taking input as matrix1:
13+
System.out.println("Enter the no. of rows of the first matrix:");
14+
int row1 = s.nextInt();
15+
System.out.println("Enter the no. of cols of the first matrix:");
16+
int col1 = s.nextInt();
17+
int[][] mat1 = new int[row1][col1];
18+
System.out.println("Enter the elements of the first matrix:");
19+
for (int i = 0; i < row1; i++) {
20+
for (int j = 0; j < col1; j++) {
21+
mat1[i][j] = s.nextInt();
22+
}
23+
}
24+
// Taking input as matrix2:
25+
System.out.println("Enter the no. of rows of the second matrix:");
26+
int row2 = s.nextInt();
27+
System.out.println("Enter the no. of cols of the second matrix:");
28+
int col2 = s.nextInt();
29+
int[][] mat2 = new int[row2][col2];
30+
System.out.println("Enter the elements of the second matrix:");
31+
for (int i = 0; i < row2; i++) {
32+
for (int j = 0; j < col2; j++) {
33+
mat2[i][j] = s.nextInt();
34+
}
35+
}
36+
37+
if (col1 == row2) {
38+
int ans[][] = matrixMul(mat1, mat2);
39+
display(ans);
40+
} else System.out.print("Invalid input");
41+
s.close();
42+
}
43+
44+
public static int[][] matrixMul(int[][] arr1, int[][] arr2) {
45+
int[][] res = new int[arr1.length][arr2[0].length];
46+
for (int i = 0; i < arr1.length; i++) {
47+
for (int j = 0; j < arr2[0].length; j++) {
48+
res[i][j] = 0;
49+
for (int k = 0; k < arr1[0].length; k++) {
50+
res[i][j] += arr1[i][k] * arr2[k][j];
51+
}
52+
}
53+
}
54+
return res;
55+
}
56+
public static void display(int [][] mat){
57+
for (int i=0;i<mat.length;i++){
58+
for (int j=0;j<mat[0].length;j++){
59+
System.out.print(mat[i][j] +" ");
60+
}
61+
System.out.println();
62+
}
63+
}
64+
65+
}
66+
67+
/*
68+
Sample Input/Output:
69+
70+
Input:
71+
2
72+
2
73+
1 2
74+
3 4
75+
2
76+
2
77+
5 6
78+
7 8
79+
80+
Output:
81+
19 22
82+
43 50
83+
84+
Time Complexity:O(n^2)
85+
Space Complexity:O(n)
86+
*/

0 commit comments

Comments
 (0)