0
0
CppProgramBeginner · 2 min read

C++ Program to Multiply Two Matrices

To multiply two matrices in C++, use nested for loops to calculate each element of the result matrix by summing the products of corresponding elements from the rows of the first matrix and columns of the second matrix, as in result[i][j] += matrix1[i][k] * matrix2[k][j]; inside three nested loops.
📋

Examples

InputMatrix1: [[1, 2], [3, 4]] Matrix2: [[5, 6], [7, 8]]
Output[[19, 22], [43, 50]]
InputMatrix1: [[2, 0], [1, 3]] Matrix2: [[1, 4], [2, 5]]
Output[[2, 8], [7, 19]]
InputMatrix1: [[0, 0], [0, 0]] Matrix2: [[1, 2], [3, 4]]
Output[[0, 0], [0, 0]]
🧠

How to Think About It

To multiply two matrices, think of each element in the result as the sum of products of elements from a row in the first matrix and a column in the second matrix. You loop through each row of the first matrix and each column of the second matrix, multiply matching elements, and add them up to get one element of the result matrix.
📐

Algorithm

1
Get the number of rows and columns for both matrices.
2
Check if the number of columns in the first matrix equals the number of rows in the second matrix.
3
Create a result matrix with the number of rows of the first matrix and columns of the second matrix.
4
For each row in the first matrix, and each column in the second matrix, multiply corresponding elements and sum them.
5
Store the sum in the result matrix at the current row and column.
6
Print the result matrix.
💻

Code

cpp
#include <iostream>
using namespace std;

int main() {
    int r1 = 2, c1 = 2, r2 = 2, c2 = 2;
    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2] = {0};

    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < c1; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    cout << "Result matrix:\n";
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            cout << result[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
🔍

Dry Run

Let's trace multiplying matrix1 [[1, 2], [3, 4]] by matrix2 [[5, 6], [7, 8]] through the code.

1

Initialize result matrix

result = [[0, 0], [0, 0]]

2

Calculate result[0][0]

result[0][0] = (1*5) + (2*7) = 5 + 14 = 19

3

Calculate result[0][1]

result[0][1] = (1*6) + (2*8) = 6 + 16 = 22

4

Calculate result[1][0]

result[1][0] = (3*5) + (4*7) = 15 + 28 = 43

5

Calculate result[1][1]

result[1][1] = (3*6) + (4*8) = 18 + 32 = 50

ElementCalculationValue
result[0][0]1*5 + 2*719
result[0][1]1*6 + 2*822
result[1][0]3*5 + 4*743
result[1][1]3*6 + 4*850
💡

Why This Works

Step 1: Matrix multiplication rule

Each element in the result matrix is the sum of products of elements from a row of the first matrix and a column of the second matrix using result[i][j] += matrix1[i][k] * matrix2[k][j];.

Step 2: Nested loops for rows and columns

The outer loops go through each row i and column j of the result matrix to fill every element.

Step 3: Inner loop for sum of products

The innermost loop k multiplies corresponding elements and adds them to get the final value for result[i][j].

🔄

Alternative Approaches

Using dynamic arrays with user input
cpp
#include <iostream>
using namespace std;

int main() {
    int r1, c1, r2, c2;
    cout << "Enter rows and columns for first matrix: ";
    cin >> r1 >> c1;
    cout << "Enter rows and columns for second matrix: ";
    cin >> r2 >> c2;
    if (c1 != r2) {
        cout << "Matrix multiplication not possible." << endl;
        return 0;
    }
    int matrix1[r1][c1], matrix2[r2][c2], result[r1][c2];

    cout << "Enter first matrix elements:\n";
    for (int i = 0; i < r1; i++)
        for (int j = 0; j < c1; j++)
            cin >> matrix1[i][j];

    cout << "Enter second matrix elements:\n";
    for (int i = 0; i < r2; i++)
        for (int j = 0; j < c2; j++)
            cin >> matrix2[i][j];

    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < c1; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    cout << "Result matrix:\n";
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            cout << result[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
This approach allows multiplying matrices of any size entered by the user but requires checking dimensions.
Using std::vector for dynamic size
cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int r1 = 2, c1 = 3, r2 = 3, c2 = 2;
    vector<vector<int>> matrix1 = {{1, 2, 3}, {4, 5, 6}};
    vector<vector<int>> matrix2 = {{7, 8}, {9, 10}, {11, 12}};
    vector<vector<int>> result(r1, vector<int>(c2, 0));

    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            for (int k = 0; k < c1; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }

    cout << "Result matrix:\n";
    for (auto &row : result) {
        for (auto &val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
    return 0;
}
Using vectors makes the code flexible for any matrix size and safer than raw arrays.

Complexity: O(r1 * c2 * c1) time, O(r1 * c2) space

Time Complexity

The program uses three nested loops: outer loops over rows of first matrix and columns of second matrix, and inner loop over columns of first matrix (or rows of second). This results in O(r1 * c2 * c1) time.

Space Complexity

The result matrix requires space proportional to the number of rows of the first matrix and columns of the second matrix, O(r1 * c2).

Which Approach is Fastest?

All approaches have the same time complexity; using vectors adds flexibility but may have slight overhead compared to raw arrays.

ApproachTimeSpaceBest For
Fixed-size arraysO(r1*c2*c1)O(r1*c2)Simple, small matrices
Dynamic arrays with user inputO(r1*c2*c1)O(r1*c2)User-defined sizes, input validation
std::vectorO(r1*c2*c1)O(r1*c2)Flexible size, safer memory management
💡
Always check that the number of columns in the first matrix equals the number of rows in the second before multiplying.
⚠️
Beginners often forget to initialize the result matrix elements to zero before summing products, causing wrong results.