How to Multiply Two Matrices in C++

In this article, we are going to learn about how to multiply two matrices in C++. We will take the input from the user for both the matrices and then perform the multiply operation on both the matrices.

Multiplication of Two Fix size Matrix

In this example, we will multiply two matrices of size n x m means n rows and m column matrices. We will ask the user to enter the values for each index, and once we have the matrices, we will multiply them index by index. After Multiplication is completed then the results will be saved in a matrix. let us understand this with the help of the below code example.

How to Multiply Two Matrices in C++


#include<iostream>
using namespace std;
int main()
{

	int Matrix1[10][10];
	int Matrix2[10][10];
	int ResultMatrix[10][10];
	int RowSize1 , ColumnSize1;
	int RowSize2 , ColumnSize2;
	int row, col;
	
	
	cout<<"Enter Row and Column Size of First Matrix (Max size 10x10): ";
    cin>>RowSize1>>ColumnSize1;
	
	cout<<"Enter Row and Column Size of Second Matrix (Max size 10x10): ";
    cin>>RowSize2>>ColumnSize2;
	

	while (ColumnSize1 != RowSize2)
    {
        cout<<"Size Mismatch Error! Number of Columns in First Matrix not equal to Number of Row in Second Matrix.\n\n";
		cout<<"Enter Row and Column Size of First Matrix: ";
		cin>>RowSize1>>ColumnSize1;
		
		cout<<"Enter Row and Column Size of Second Matrix: ";
		cin>>RowSize2>>ColumnSize2;
    }
	
	cout<<"Please enter the Elements of First Matrix: ";
    for(row=0; row< RowSize1; ++row)
    {
        for(col=0; col< ColumnSize1; ++col)
            cin>> Matrix1[row][col];
    }
	
	
    cout<<"Please enter the Elements Second Matrix: ";
    for(row=0; row< RowSize2; ++row)
    {
        for(col=0; col< ColumnSize2; ++col)
            cin>>Matrix2[row][col];
    }
	

    for(row = 0; row < RowSize1; ++row)
        for(col = 0; col < ColumnSize2; ++col)
        {
            ResultMatrix[row][col]=0;
        }
	
    for(row=0; row< RowSize1; ++row)
        for(col=0; col< ColumnSize2; ++col)
			for(int Recol=0; Recol< ColumnSize1; ++Recol)
			{
				ResultMatrix[row][col] += Matrix1[row][Recol] * Matrix2[Recol][col];
				
			}
			

    
	
    cout<<"The Resulted Matrix after Multiplication is:\n";
    for(row=0; row< RowSize1; ++row)
        for(col=0; col< ColumnSize2; ++col)
        {
            cout<< ResultMatrix[row][col]<<" ";
            if(col == ColumnSize2-1)
            cout<<"\n\n";
        }
    
    return 0;
}

Output

Enter Row and Column Size of First Matrix (Max size 10x10): 2
2
Enter Row and Column Size of Second Matrix (Max size 10x10): 2
2
Please enter the Elements of First Matrix: 1
2
3
4
Please enter the Elements Second Matrix: 4
3
2
1
The Resulted Matrix after Multiplication is:
8 5 

20 13