Skip to content
This repository was archived by the owner on Nov 25, 2022. It is now read-only.

Commit 96771b0

Browse files
authored
Merge pull request #199 from iamatifmoin/master
Added program for Matrix Multiplication (Helps is issue #1 )
2 parents 399561e + 98b476b commit 96771b0

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Java program to multiply two square matrices.
2+
3+
import java.io.*;
4+
5+
class matrixmultiplication {
6+
7+
// Function to print Matrix
8+
static void printMatrix(int M[][],
9+
int rowSize,
10+
int colSize) {
11+
for (int i = 0; i < rowSize; i++) {
12+
for (int j = 0; j < colSize; j++)
13+
System.out.print(M[i][j] + " ");
14+
15+
System.out.println();
16+
}
17+
}
18+
19+
// Function to multiply
20+
// two matrices A[][] and B[][]
21+
static void multiplyMatrix(
22+
int row1, int col1, int A[][],
23+
int row2, int col2, int B[][]) {
24+
int i, j, k;
25+
26+
// Print the matrices A and B
27+
System.out.println("\nMatrix A:");
28+
printMatrix(A, row1, col1);
29+
System.out.println("\nMatrix B:");
30+
printMatrix(B, row2, col2);
31+
32+
// Check if multiplication is Possible
33+
if (row2 != col1) {
34+
35+
System.out.println(
36+
"\nMultiplication Not Possible");
37+
return;
38+
}
39+
40+
// Matrix to store the result
41+
// The product matrix will
42+
// be of size row1 x col2
43+
int C[][] = new int[row1][col2];
44+
45+
// Multiply the two matrices
46+
for (i = 0; i < row1; i++) {
47+
for (j = 0; j < col2; j++) {
48+
for (k = 0; k < row2; k++)
49+
C[i][j] += A[i][k] * B[k][j];
50+
}
51+
}
52+
53+
// Print the result
54+
System.out.println("\nResultant Matrix:");
55+
printMatrix(C, row1, col2);
56+
}
57+
58+
// Driver code
59+
public static void main(String[] args) {
60+
61+
int row1 = 4, col1 = 3, row2 = 3, col2 = 4;
62+
63+
int A[][] = { { 1, 1, 1 },
64+
{ 2, 2, 2 },
65+
{ 3, 3, 3 },
66+
{ 4, 4, 4 } };
67+
68+
int B[][] = { { 1, 1, 1, 1 },
69+
{ 2, 2, 2, 2 },
70+
{ 3, 3, 3, 3 } };
71+
72+
multiplyMatrix(row1, col1, A,
73+
row2, col2, B);
74+
}
75+
}

0 commit comments

Comments
 (0)