Write a C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

Matrix multiplication is a fundamental operation in linear algebra and is used in many fields such as image processing, computer graphics, and machine learning.

In this tutorial, we will learn how to multiply two matrices using multi-dimensional arrays in C++.

Before we get started, let’s first understand what a matrix is. A matrix is a rectangular array of numbers arranged in rows and columns.

The size of the matrix is given by the number of rows and columns. For example, a matrix with 2 rows and 3 columns can be represented as follows:

1 2 3
4 5 6

To multiply two matrices, we need to ensure that the number of columns of the first matrix is equal to the number of rows of the second matrix.

The resulting matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.

Let’s now see how we can multiply two matrices using multi-dimensional arrays in C++.

We will use a nested loop to iterate through the rows and columns of the matrices and perform the multiplication. Here’s the code:

#include <iostream>
using namespace std;

int main() {
    int m1[10][10], m2[10][10], product[10][10];
    int r1, c1, r2, c2;

    cout << "Enter the number of rows and columns of first matrix: ";
    cin >> r1 >> c1;

    cout << "Enter the elements of first matrix: " << endl;
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c1; j++) {
            cin >> m1[i][j];
        }
    }

    cout << "Enter the number of rows and columns of second matrix: ";
    cin >> r2 >> c2;

    if (c1 != r2) {
        cout << "Matrices cannot be multiplied!";
        return 0;
    }

    cout << "Enter the elements of second matrix: " << endl;
    for (int i = 0; i < r2; i++) {
        for (int j = 0; j < c2; j++) {
            cin >> m2[i][j];
        }
    }

    // Perform matrix multiplication
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            product[i][j] = 0;
            for (int k = 0; k < c1; k++) {
                product[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }

    // Display the result
    cout << "Product of the matrices: " << endl;
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            cout << product[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

In this code, we first declare three multi-dimensional arrays m1, m2, and product to store the input matrices and the result.

We also declare variables r1, c1, r2, and c2 to store the dimensions of the matrices.

We then use the cin function to read the input matrices and display an error message if the matrices cannot be multiplied.

Next, we use a nested loop to perform the matrix multiplication and store the result in the product array. Finally, we display the result using another loop.