Using Multi Dimensional Arrays For Multiplication of Two Matrices in C++

Write a C++ program that multiplies two matrices with the help of multi-dimensional arrays.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int a[10][10], b[10][10], ans[10][10], row1, col1, row2, col2, i, j, k;
    cout << "Insert rows and columns of matrix 1:\n";
    cin >> row1 >> col1;
    cout << "Insert rows and columns of matrix 2:\n";
    cin >> row2 >> col2;
    // CHECK!!! column of first matrix must be equal to row of second matrix,
    while (col1!=row2)
    {
        cout << "ERROR!! row of matrix 2 not equal to column of matrix 1.";
        cout << "Insert rows and columns of matrix 1 again:\n";
        cin >> row1 >> col1;
        cout << "Insert rows and columns of matrix 2 again:\n";
        cin >> row2 >> col2;
    }
    // Storing matrix 1
    cout << endl << "Insert values of matrix 1:\n" << endl;
    for(i = 0; i < row1; ++i)
        for(j = 0; j < col1; ++j)
        {
            cout << "position " << i + 1 << j + 1 << " : ";
            cin >> a[i][j];
        }
    // Storing matrix 2
    cout << endl << "Insert values of matrix 2:\n" << endl;
    for(i = 0; i < row2; ++i)
        for(j = 0; j < col2; ++j)
        {
            cout << "position " << i + 1 << j + 1 << " : ";
            cin >> b[i][j];
        }
    // Initializing to 0.
    for(i = 0; i < row1; ++i)
        for(j = 0; j < col2; ++j)
        {
            ans[i][j]=0;
        }
    // multiplying and storing in array ans.
    for(i = 0; i < row1; ++i)
        for(j = 0; j < col2; ++j)
            for(k = 0; k < col1; ++k)
            {
                ans[i][j] += a[i][k] * b[k][j];
            }
    cout << endl << "Multiplication of Matrix: " << endl;
    for(i = 0; i < row1; ++i)
    for(j = 0; j < col2; ++j)
    {
        cout << " " << ans[i][j];
        if(j == col2-1)
        cout << endl;
    }
    return 0;
}
Click Here to View the Output:
Insert rows and columns of matrix 1:
 2
 1
 Insert rows and columns of matrix 2:
 1
 2
 Insert values of matrix 1:
 position 11 : 5
 position 21 : 2
 Insert values of matrix 2:
 position 11 : 4
 position 12 : 6
 Multiplication of Matrix:
  20 30
  8 12
Click Here to View the Explanation:
  • To multiply matrices, it should first be confirmed that the number of columns of the first matrix is equal to the number of rows of the second matrix.
  • The user is asked to enter the number of rows and columns for the first and second matrices. The matrices are checked if they can be multiplied.
  • If the number is not equal, the user is asked to input new values.
  • for loops are used to store elements of the matrices and another is used to initialize the elements of a matrix to 0.
  • The result after the multiplication of two matrices is displayed on the screen.
  • This program can be debugged easily if a function is created and called onto main () function.
%d bloggers like this: