# Program to check if two given matrices are identical in C++

Given two matrix M1[r][c] and M2[r][c] with ‘r’ number of rows and ‘c’ number of columns, we have to check that the both given matrices are identical or not. If they are identical then print “Matrices are identical” else print “Matrices are not identical”

## Identical Matrix

Two matrices M1 and M2 are be called identical when −

• Number of rows and columns of both matrices are same.
• The values of M1[i][j] are equal to M2[i][j].

Like in the given figure below both matrices m1 and m2 of 3x3 are identical −

$$M1[3][3]=\begin{bmatrix} 1 & 2 & 3 \ 4 & 5 & 6 \ 7 & 8 & 9 \ \end {bmatrix} \:\:\:\:M2[3][3] =\begin{bmatrix} 1 & 2 & 3 \ 4 & 5 & 6 \ 7 & 8 & 9 \ \end{bmatrix}$$

## Example

Input: a[n][n] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{3,3, 3, 3},
{3,3, 3, 3}};
b[n][n]= { {2, 2, 2, 2},
{2, 2, 2, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}};
Output: matrices are identical
Input: a[n][n] = { {2, 2, 2, 2},
{2, 2, 1, 2},
{3,3, 3, 3},
{3,3, 3, 3}};
b[n][n]= { {2, 2, 2, 2},
{2, 2, 5, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}};
Output: matrices are not identical

## Approach

Iterate both matrices a[i][j] and b[i][j], and check a[i][j]==b[i][j] if true for all then print they are identical else print they are not identical.

## Algorithm

Start
Step 1 -> define macro as #define n 4
Step 2 -> Declare function to check matrix is same or not
int check(int a[][n], int b[][n])
declare int i, j
Loop For i = 0 and i < n and i++
Loop For j = 0 and j < n and j++
IF (a[i][j] != b[i][j])
return 0
End
End
End
return 1
Step 3 -> In main()
Declare variable asint a[n][n] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}}
Declare another variable as int b[n][n] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}}
IF (check(a, b))
Print matrices are identical
Else
Print matrices are not identical
Stop

## Example

#include <bits/stdc++.h>
#define n 4
using namespace std;
// check matrix is same or not
int check(int a[][n], int b[][n]){
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[i][j] != b[i][j])
return 0;
return 1;
}
int main(){
int a[n][n] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}};
int b[n][n] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{3, 3, 3, 3},
{3, 3, 3, 3}};
if (check(a, b))
cout << "matrices are identical";
else
cout << "matrices are not identical";
return 0;
}

## Output

matrices are identical

Updated on: 23-Sep-2019

770 Views