Multiplication of Two Matrix in C++ of Same Dimensions using For loop
ADVERTISEMENTS
Multiplication of two matrix in C++ of same dimensions using for loop. In this article, you will learn how to make program of multiplication of two matrix in c++ of same dimensions using for loop.
Matrix Multiplication Formula
{ M1 } x { M2 } = { M3 }
Source Code
// Multiplication of Two Matrix in C++ of Same Dimensions using For loop
#include <iostream>
using namespace std;
int main() {
int r, c, i, j, k;
// r - To store the number of rows
// c - To store the number of columns
cout << "Enter the number of rows & columns of the matrix::\n";
cin >> r >> c;
int x[r][c], y[r][c], m[r][c];
// x - To store the first matrix elements
// y - To store the second matrix elements
// m - To store the multiplication of matrices
cout << "\n---Enter the first matrix's elements---\n";
for (i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
cin >> x[i][j];
}
}
cout << "---Enter the second matrix's elements---\n";
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
cin >> y[i][j];
}
}
cout << "\n\n-----The multiplication of the matrices is-----\n\n";
// It's the calculation of matrices's multiplications
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
m[i][j] = 0;
for(k = 0; k < c; k++) {
m[i][j] += x[i][k] * y[k][j];
}
}
}
// This will display matrices's outputs
for(i = 0; i < r; i++) {
cout << "\t";
for(j = 0; j < c; j++) {
cout << m[i][j] << "\t";
}
cout << "\n\n";
}
return 0;
}
Output
Enter the number of rows & columns of the matrix::
4
3
---Enter the first matrix's elements---
12 54 65
32 54 65
23 54 65
32 54 56
---Enter the second matrix's elements---
23 88 56
23 55 89
23 65 23
54 24 76
-----The multiplication of the matrices is-----
3013 8251 6973
3473 10011 8093
3266 9219 7589
3266 9426 7886