C++ Program to Perform Matrix Multiplication

C++ Program to Perform Matrix Multiplication

Matrix multiplication is a fundamental operation in mathematics and computer science, widely used in areas such as computer graphics, engineering simulations, and scientific computing. Unlike matrix addition or subtraction, multiplication involves multiplying rows of the first matrix by columns of the second matrix and summing the results. Learning how to perform matrix multiplication in C++ is an excellent way for beginners to understand nested loops, array handling, and mathematical logic. By practicing matrix multiplication, you also build a foundation for more complex topics like linear algebra, image processing, and algorithm design.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Program 1: Matrix Multiplication Using User Input

This program allows users to input two matrices and calculates their product. It demonstrates how nested loops and arrays work together for more complex operations in C++.

#include <iostream>

using namespace std;

int main() {

    int rows1, cols1, rows2, cols2;

    cout << "Enter number of rows and columns of first matrix: " << endl;
    cin >> rows1 >> cols1;

    cout << "Enter number of rows and columns of second matrix: " << endl;
    cin >> rows2 >> cols2;

    if(cols1 != rows2) {

        cout << "Matrix multiplication not possible! Columns of first matrix must equal rows of second matrix." << endl;
        return 0;

    }

    int matrix1[rows1][cols1], matrix2[rows2][cols2], product[rows1][cols2] = {0};

    cout << "Enter elements of first matrix:" << endl;

    for(int i = 0; i < rows1; i++)
        for(int j = 0; j < cols1; j++)
            cin >> matrix1[i][j];

    cout << "Enter elements of second matrix:" << endl;
    
    for(int i = 0; i < rows2; i++)
        for(int j = 0; j < cols2; j++)
            cin >> matrix2[i][j];

    for(int i = 0; i < rows1; i++) {

        for(int j = 0; j < cols2; j++) {

            for(int k = 0; k < cols1; k++) {
                product[i][j] += matrix1[i][k] * matrix2[k][j];
            }

        }

    }

    cout << "Product of the matrices:" << endl;

    for(int i = 0; i < rows1; i++) {

        for(int j = 0; j < cols2; j++) {
            cout << product[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

In this program, the user enters the size and elements of two matrices. The program checks if multiplication is possible by comparing the number of columns of the first matrix with the number of rows of the second matrix. Nested loops calculate the product by multiplying corresponding elements and summing them. Beginners learn how nested iterations and array indexing can handle complex mathematical operations.

Program 2: Matrix Multiplication with Predefined Matrices

Sometimes, using predefined matrices helps beginners focus on logic without worrying about user input. This program demonstrates multiplication of two 2×2 matrices using predefined values.

#include <iostream>

using namespace std;

int main() {

    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int product[2][2] = {0};

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {

            for(int k = 0; k < 2; k++) {

                product[i][j] += matrix1[i][k] * matrix2[k][j];

            }

        }

    }

    cout << "Product of the predefined matrices:" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << product[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

This example uses predefined matrices for simplicity. Nested loops perform the multiplication step by step, storing the results in the product matrix. Beginners can clearly see how rows of the first matrix multiply with columns of the second matrix, reinforcing their understanding of the mathematical logic behind matrix multiplication.

Program 3: Matrix Multiplication for Larger Predefined Matrices

For more practice, this program multiplies two 3×3 matrices with predefined values, showing how matrix multiplication scales to larger data.

#include <iostream>

using namespace std;

int main() {

    int matrix1[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
    int matrix2[3][3] = {{9,8,7}, {6,5,4}, {3,2,1}};
    int product[3][3] = {0};

    for(int i = 0; i < 3; i++) {

        for(int j = 0; j < 3; j++) {

            for(int k = 0; k < 3; k++) {

                product[i][j] += matrix1[i][k] * matrix2[k][j];

            }

        }

    }

    cout << "Product of the 3x3 matrices:" << endl;

    for(int i = 0; i < 3; i++) {

        for(int j = 0; j < 3; j++) {
            cout << product[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

This program demonstrates how nested loops can systematically handle larger matrices. Beginners learn to manage multiple layers of iteration and understand how the formula for matrix multiplication is implemented in code.

Program 4: Colorful Matrix Display

This program multiplies two predefined 2×2 matrices and displays the original matrices and their product in different colors using ANSI escape codes. It’s visually engaging and makes it easier for beginners to follow the calculations.

#include <iostream>

using namespace std;

int main() {

    int matrix1[2][2] = {{1, 2}, {3, 4}};
    int matrix2[2][2] = {{5, 6}, {7, 8}};
    int product[2][2] = {0};

    // Calculate product of matrices
    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {

            for(int k = 0; k < 2; k++) {
                product[i][j] += matrix1[i][k] * matrix2[k][j];
            }

        }

    }

    // Display first matrix in blue
    cout << "\033[1;34mMatrix 1:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;34m" << matrix1[i][j] << " \033[0m";
        }

        cout << endl;

    }

    // Display second matrix in green
    cout << "\033[1;32mMatrix 2:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;32m" << matrix2[i][j] << " \033[0m";
        }

        cout << endl;

    }

    // Display product matrix in yellow
    cout << "\033[1;33mProduct of Matrices:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;33m" << product[i][j] << " \033[0m";
        }

        cout << endl;

    }

    return 0;

}

In this colorful program, two predefined matrices are multiplied element by element using nested loops. ANSI escape codes like \033[1;34m and \033[1;32m color the console output so the first matrix appears in blue, the second in green, and the product in yellow. This visual distinction helps beginners track calculations and understand the matrix multiplication process clearly.

Frequently Asked Questions (FAQ)

Matrix multiplication can seem tricky for beginners. Here are some common questions and answers to clarify concepts.

Q1: What is matrix multiplication?
A1: Matrix multiplication combines two matrices by multiplying rows of the first matrix with columns of the second matrix and summing the results.

Q2: Can I multiply matrices of different sizes?
A2: Yes, but only if the number of columns in the first matrix equals the number of rows in the second matrix.

Q3: What is the result size of the product?
A3: The resulting matrix has the same number of rows as the first matrix and the same number of columns as the second matrix.

Q4: Why are nested loops used?
A4: Nested loops handle the multiple levels of iteration required to multiply rows by columns and sum the products.

Q5: Why use predefined matrices?
A5: Predefined matrices help beginners focus on learning the multiplication logic without worrying about user input.

Conclusion

Matrix multiplication in C++ is an essential skill that helps beginners understand arrays, nested loops, and mathematical operations. By practicing with user input, predefined matrices, and larger datasets, beginners can strengthen their understanding of structured data and develop problem-solving skills. Regular practice with matrix multiplication prepares you for more advanced topics in C++, such as linear algebra, graphics programming, and algorithm development.

Additional & References

Beginners are encouraged to experiment with different matrix sizes and try variations like identity matrices, zero matrices, and larger datasets. This practice will deepen understanding of matrix operations and prepare for more complex programming challenges.

Scroll to Top