Matrix Multiplication in C++
This page provides a C++ program to multiply two matrices. Matrix multiplication involves the dot product of rows and columns. The resulting matrix will have dimensions based on the row count of the first matrix and the column count of the second matrix.
Program Explanation
The program consists of the following parts:
- Reading dimensions and elements of the matrices from the user.
- Initializing the result matrix with zeroes.
- Performing the matrix multiplication operation.
- Displaying the resultant matrix.
Program Structure
Here is the detailed structure of the C++ program:
// Program to multiply two matrices in C++
#include <iostream>
#include <vector>
using namespace std;
// Function to multiply two matrices
vector<vector<int>> multiplyMatrices(const vector<vector<int>>& A, const vector<vector<int>>& B) {
int n = A.size();
int m = B[0].size();
int p = A[0].size();
// Initialize result matrix with zeros
vector<vector<int>> C(n, vector<int>(m, 0));
// Multiply matrices
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int k = 0; k < p; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
int main() {
int n, p, m;
// Input dimensions of matrix A (n x p)
cout << "Enter the number of rows and columns of the first matrix (n p): ";
cin >> n >> p;
vector<vector<int>> A(n, vector<int>(p));
// Input elements of matrix A
cout << "Enter elements of the first matrix:" << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < p; ++j) {
cin >> A[i][j];
}
}
// Input dimensions of matrix B (p x m)
cout << "Enter the number of columns of the second matrix (m): ";
cin >> m;
vector<vector<int>> B(p, vector<int>(m));
// Input elements of matrix B
cout << "Enter elements of the second matrix:" << endl;
for (int i = 0; i < p; ++i) {
for (int j = 0; j < m; ++j) {
cin >> B[i][j];
}
}
// Multiply matrices A and B
vector<vector<int>> C = multiplyMatrices(A, B);
// Output the result matrix C
cout << "Resultant matrix:" << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
Code Explanation
The multiplyMatrices
function takes two matrices A
and B
as input and returns their product C
. The main function handles input and output:
vector<vector<int>> C(n, vector<int>(m, 0));
: Initializes a matrix of sizen x m
with all zeros.- Triple nested loops: Iterate over the rows of
A
, columns ofB
, and elements of rows/columns to perform the multiplication and summation. - Input and output sections: Read matrix dimensions and elements, and display the result.
Sample Input and Output
Enter the number of rows and columns of the first matrix (n p): 2 3
Enter elements of the first matrix:
1 2 3
4 5 6
Enter the number of columns of the second matrix (m): 2
Enter elements of the second matrix:
7 8
9 10
11 12
Resultant matrix:
58 64
139 154