In this tutorial, we will learn and write a C++ program to print the multiplication of two matrices. Before that, you may go through the following topics in C++ programming:
The program takes the user input for the number of rows and columns and then the elements for both the matrices.
C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays
Multiplication of matrix in C++.
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 | #include <iostream> using namespace std; int main() { int a[10][10], b[10][10], mul[10][10]; int row, col, i, j, k; cout << "Enter the no. of rows: "; cin >> row; cout << "Enter the no. of columns: "; cin >> col; // 1st matrix user input cout << endl << "Enter 1st Matrix elements: " << endl; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) cin >> a[i][j]; } // 2nd matrix user input cout << endl << "Enter 2nd Matrix elements: " << endl; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) cin >> b[i][j]; } // matrix multiplication for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { mul[i][j] = 0; for (k = 0; k < col; k++) mul[i][j] += a[i][k] *b[k][j]; } } //Displaying the result cout << "Multiplication of matrix" << endl; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) cout << mul[i][j] << " "; cout << "\n"; } return 0; } |
Output:
Enter the no. of rows: 3
Enter the no. of columns: 3
Enter 1st Matrix elements:
2 3 6
2 3 6
2 3 6
Enter 2nd Matrix elements:
1 2 3
1 2 3
1 2 3
Multiplication of matrix
11 22 33
11 22 33
11 22 33