C++ Program to Multiply Two Matrices

1. Introduction

Matrix multiplication is a fundamental operation in linear algebra. In computing, it's frequently used in graphics processing, solving systems of linear equations, and many other applications. This post will guide you through a C++ program that multiplies two matrices.

2. Program Overview

1. The program first ensures the matrices can be multiplied by checking their dimensions.

2. It then initializes a result matrix to store the multiplication result.

3. Using nested loops, each cell in the result matrix is calculated as the sum of products of rows and columns from the two matrices.

4. The program displays the resulting matrix.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int r1, c1, r2, c2;

    // Get matrix dimensions from user
    cout << "Enter rows and columns for first matrix: ";
    cin >> r1 >> c1;
    cout << "Enter rows and columns for second matrix: ";
    cin >> r2 >> c2;

    // Ensure matrices can be multiplied
    if(c1 != r2) {
        cout << "Error! Column of first matrix is not equal to row of second.";
        return -1;
    }

    double m1[r1][c1], m2[r2][c2], result[r1][c2];

    // Get elements of first matrix from user
    cout << "Enter elements of first matrix:" << endl;
    for(int i=0; i<r1; ++i)
        for(int j=0; j<c1; ++j)
            cin >> m1[i][j];

    // Get elements of second matrix from user
    cout << "Enter elements of second matrix:" << endl;
    for(int i=0; i<r2; ++i)
        for(int j=0; j<c2; ++j)
            cin >> m2[i][j];

    // Multiply matrices
    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] += m1[i][k] * m2[k][j];
        }

    // Display resulting matrix
    cout << "Output Matrix:" << endl;
    for(int i=0; i<r1; ++i) {
        for(int j=0; j<c2; ++j)
            cout << result[i][j] << " ";
        cout << endl;
    }

    return 0;
}

Output:

Enter rows and columns for first matrix: 2 2
Enter rows and columns for second matrix: 2 2
Enter elements of first matrix:
1 2 3 4
Enter elements of second matrix:
5 6 7 8
Output Matrix:
19 22
43 50 

4. Step By Step Explanation

1. Dimensions Verification: Before attempting to multiply, it's crucial to ensure the matrices can be multiplied. This is done by checking if the number of columns in the first matrix is equal to the number of rows in the second matrix.

2. Input Collection: After the matrices' dimensions are provided, their individual elements are collected.

3. Matrix Multiplication: Nested loops are used to calculate the result matrix's individual cells. For each cell, the program computes the sum of the products of corresponding elements from the first matrix's row and the second matrix's column.

4. Result Display: Finally, the program displays the resulting matrix.

Comments