Multiplication of two matrices - C++ Program

Q. Write a C++ program to print the multiplication of two matrices.

Answer:

Following program is displaying the multiplication of two matrices.

#include<iostream>
using namespace std;
int main()
{
        int m1[3][3], m2[3][3], m3[3][3], sum=0, i, j, k;
        cout<<"\n Enter First Matrix Elements : \n";
        for(i=0; i<3; i++)
        {
                for(j=0; j<3; j++)
                {
                        cout<<" ";
                        cin>>m1[i][j];
                }
        }
        cout<<"\n Enter Second Matrix Elements : \n";
        for(i=0; i<3; i++)
        {
                for(j=0; j<3; j++)
                {
                        cout<<" ";
                        cin>>m2[i][j];
                }
        }
        cout<<"\n\n Multiplication of Two Matrices : \n";
        for(i=0; i<3; i++)
        {
                for(j=0; j<3; j++)
                {
                        sum=0;
                        for(k=0; k<3; k++)
                        {
                                sum = sum + m1[i][k] * m2[k][j];
                        }
                        m3[i][j] = sum;
                }
        }
        for(i=0; i<3; i++)
        {
                for(j=0; j<3; j++)
                {
                        cout<<" ";
                        cout<<m3[i][j]<<"\t";
                }
                cout<<"\n";
        }
        return 0;
}


Output:

two dimensional multiplication

Explanation:

multiplication of two matrices

  • The above figure shows the work flow or structure of matrix and how actually it works. The above figure represents multiplication of two matrices. For multiplication of two matrix, it requires first matrix's first row and second matrix's first column, then multiplying the members and the last step is addition of members as shown in the figure.
  • In the above figure, we match first members {1 and 7}, then multiply them, likewise for the second members {2 and 6} and the third members {4 and 3} and finally sum them up.
  • After multiplication of two matrices, the result will display in the third matrix as shown in the above diagram.