Skip to content

Commit 7810d80

Browse files
author
codehouseindia
authored
Merge pull request codehouseindia#68 from devmitanshu/master
Create productofmatrix.java
2 parents a90b89f + a5ce204 commit 7810d80

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

productofmatrix.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
public class ProdMatrix
2+
{
3+
public static void main(String[] args) {
4+
int row1, col1, row2, col2;
5+
//Initialize matrix a
6+
int a[][] = {
7+
{1, 3, 2},
8+
{3, 1, 1},
9+
{1, 2, 2}
10+
};
11+
12+
//Initialize matrix b
13+
int b[][] = {
14+
{2, 1, 1},
15+
{1, 0, 1},
16+
{1, 3, 1}
17+
};
18+
19+
//Calculates number of rows and columns present in first matrix
20+
row1 = a.length;
21+
col1 = a[0].length;
22+
23+
//Calculates the number of rows and columns present in the second matrix
24+
25+
row2 = b.length;
26+
col2 = b[0].length;
27+
28+
//For two matrices to be multiplied,
29+
//number of columns in first matrix must be equal to number of rows in second matrix
30+
if(col1 != row2){
31+
System.out.println("Matrices cannot be multiplied");
32+
}
33+
else{
34+
//Array prod will hold the result
35+
int prod[][] = new int[row1][col2];
36+
37+
//Performs product of matrices a and b. Store the result in matrix prod
38+
for(int i = 0; i < row1; i++){
39+
for(int j = 0; j < col2; j++){
40+
for(int k = 0; k < row2; k++){
41+
prod[i][j] = prod[i][j] + a[i][k] * b[k][j];
42+
}
43+
}
44+
}
45+
46+
System.out.println("Product of two matrices: ");
47+
for(int i = 0; i < row1; i++){
48+
for(int j = 0; j < col2; j++){
49+
System.out.print(prod[i][j] + " ");
50+
}
51+
System.out.println();
52+
}
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)