Write C++ Program to check whether two matrices are equal or not

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
using namespace std;
 
#define size 2 // Matrix size declaration
 
int main()
{
    int A[size][size];
    int B[size][size];
 
    int row, col, isEqual;
 
    // Input elements in first matrix from user
    cout<<"Enter elements in matrix A of size "<<size<<" x "<<size<<"\n";
    for(row=0; row<size; row++)
    {
        for(col=0; col<size; col++)
        {
            cin>>A[row][col];
        }
    }
 
    // Input elements in second matrix from user
    cout<<"Enter elements in matrix B of size"<<size<<" x "<<size<<"\n";
    for(row=0; row<size; row++)
    {
        for(col=0; col<size; col++)
        {
            cin>>B[row][col];
        }
    }
 
    // Assumes that the matrices are equal
    isEqual = 1;
 
    for(row=0; row<size; row++)
    {
        for(col=0; col<size; col++)
        {
 
            //If the corresponding entries of matrices are not equal
 
            if(A[row][col] != B[row][col])
            {
                isEqual = 0;
                break;
            }
        }
    }
 
    /*
     * Checks the value of isEqual
     * As per our assumption if isEqual contains 1 means both are equal
     * If it contains 0 means both are not equal
     */
    if(isEqual == 1)
    {
        cout<<"\nMatrix A is equal to Matrix B";
    }
    else
    {
        cout<<"\nMatrix A is not equal to Matrix B";
    }
 
    return 0;
}
 

Result

Write C++ Program to check whether two matrices are equal or not
Write C++ Program to check whether two matrices are equal or not

Leave a Comment

x