Matrix Multiplication
Matrix Multiplication in C++ (Multiply Two Matrix)
IntermediateTopic: Array Operations Programs
C++ Matrix Multiplication Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int rows1 = 2, cols1 = 3;
int rows2 = 3, cols2 = 2;
int matrix1[2][3] = {{1, 2, 3}, {4, 5, 6}};
int matrix2[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int result[2][2] = {{0, 0}, {0, 0}};
// Matrix multiplication
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
cout << "Result matrix:" << endl;
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}Output
Result matrix: 58 64 139 154
Understanding Matrix Multiplication
Matrix multiplication requires the number of columns of the first matrix to equal the number of rows of the second matrix. The result is calculated by multiplying corresponding elements and summing them.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.