How to check two matrices are equal or not in C++

In this article, we are going to learn about How to check two matrices are equal or not in C++. We will take the input from the user for both the matrices and then we will perform the comparison operation on both the matrices.

Comparison of Two Fix size Matrix in C++


In this example, we are going to Compare two matrices of size nxm 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 Compare the index of the element by index. let us understand this with the help of the below code example.

How to check two matrices are equal or not in C++ program


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

	int Matrix1[10][10];
	int Matrix2[10][10];
	
	int RowSize1 , ColumnSize1;
	int RowSize2 , ColumnSize2;
	int row, col;
	bool isEqual = true;
	
	
	cout<<"Enter Row and Column Size of First Matrix: ";
    cin>>RowSize1>>ColumnSize1;
	
	cout<<"Enter Row and Column Size of Second Matrix: ";
    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<ColumnSize1; col++)
        {
            if(Matrix1[row][col] != Matrix2[row][col])
            {
                isEqual = false;
                break;
            }
        }
    }
	
	if(isEqual == true)
    {
        cout<<"\n First Matrix is equal to Second Matrix";
    }
    else
    {
        cout<<"\n First Matrix is Not equal to Second Matrix";
    }
	
	
    return 0;
}

Output

Enter Row and Column Size of First Matrix: 2
3
Enter Row and Column Size of Second Matrix: 2
2
Size Mismatch Error! Number of Columns in First Matrix not equal to Number of Row in Second Matrix.

Enter Row and Column Size of First Matrix: 3
3
Enter Row and Column Size of Second Matrix: 3
3
Please enter the Elements of First Matrix: 1
2
3
4
5
6
7
8
9
Please enter the Elements Second Matrix: 1
2
3
4
5
6
7
8
9

 First Matrix is equal to Second Matrix