forked from avinash201199/DSA-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_multiplication.cpp
More file actions
87 lines (69 loc) · 2.19 KB
/
matrix_multiplication.cpp
File metadata and controls
87 lines (69 loc) · 2.19 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
80
81
82
83
84
85
86
87
/*
* This C++ program can multiply any two square or rectangular matrices.
* The below program multiplies two square matrices of size 4 * 4.
* There is also an example of rectangular matrix for the same code (commented below)
* We can change the number of rows and columns (from MACROs) for Matrix-1
* and Matrix-2 for different dimensions.
*/
#include <iostream>
using namespace std;
//According to your Matrix Dimensions for mat1[R1][C1] and mat2[R2][C2]
#define R1 4 // number of rows in Matrix-1
#define C1 4 // number of columns in Matrix-1
#define R2 4 // number of rows in Matrix-2
#define C2 4 // number of columns in Matrix-2
void mulMat(int mat1[][C1], int mat2[][C2]) {
int rslt[R1][C2];
cout << "Multiplication of given two matrices is:\n" << endl;
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
rslt[i][j] = 0;
for (int k = 0; k < R2; k++) {
rslt[i][j] += mat1[i][k] * mat2[k][j];
}
cout << rslt[i][j] << "\t";
}
cout << endl;
}
}
int main(void)
{
// Square Matrices
// R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these values in MACROs)
int mat1[R1][C1] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
int mat2[R2][C2] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
/*
// Rectangular Matrices
// R1 = 3, C1 = 4 and R2 = 4, C2 = 3 (Update these values in MACROs)
int mat1[R1][C1] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}
};
int mat2[R2][C2] = {
{1, 1, 1},
{2, 2, 2},
{3, 3, 3},
{4, 4, 4}
};
*/
if (C1 != R2) {
cout << "The number of columns in Matrix-1 must be equal to the number of rows in "
"Matrix-2" << endl;
cout << "Please update MACROs according to your array dimension in #define section"
<< endl;
exit(EXIT_FAILURE);
}
mulMat(mat1, mat2);
return 0;
}