C++ Program To Check if Two Matrices are Identical

Last Updated : 20 Aug, 2026

Given two matrices, the task is to check whether they are identical or not. Two matrices are identical if they have the same dimensions and all corresponding elements are equal.

  • Both matrices must have the same number of rows and columns.
  • Each corresponding pair of elements must be equal.

Examples:

Input:

A = {{1, 2},
{3, 4}}

B = {{1, 2},
{3, 4}}

Output: Matrices are identical

Input:

A = {{1, 2},
{3, 4}}

B = {{1, 2},
{3, 5}}

Output: Matrices are not identical

Approach

The idea is to compare the corresponding elements of both matrices.

  • Traverse both matrices using nested loops.
  • Compare the elements at each position (i, j).
  • If any pair of corresponding elements is different, the matrices are not identical.
  • If all corresponding elements are equal, the matrices are identical.
C++
#include <iostream>
using namespace std;

#define N 4

// Returns true if both matrices are identical
bool areSame(int A[][N], int B[][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (A[i][j] != B[i][j])
                return false;
        }
    }

    return true;
}

// Driver code
int main()
{
    int A[N][N] = {
        {1, 1, 1, 1},
        {2, 2, 2, 2},
        {3, 3, 3, 3},
        {4, 4, 4, 4}
    };

    int B[N][N] = {
        {1, 1, 1, 1},
        {2, 2, 2, 2},
        {3, 3, 3, 3},
        {4, 4, 4, 4}
    };

    if (areSame(A, B))
        cout << "Matrices are identical";
    else
        cout << "Matrices are not identical";

    return 0;
} 

Output
Matrices are identical

Explanation

  • areSame() compares the corresponding elements of matrices A and B.
  • It returns false as soon as a mismatch is found; otherwise, it returns true.
  • main() initializes the matrices, calls areSame(), and prints the result.
Try It Yourself
redirect icon
Comment