Home » Interview Questions » Matrix Interview Questions » Check if two given matrices are identical

Check if two given matrices are identical


()

Given two matrices, we will write a function to check whether the two matrices are identical or not. That is, if all the elements in the respective positions of the two matrices are same, then we say that they are identical.

Example

Input

A[4][4] =     {{1, 4, 7, 9},
{1, 6, 7, 6},
{6, 3, 7, 12},
{4, 4, 4, 4}};

B[4][4] =     {{1, 4, 7, 9},
{1, 6, 7, 6},
{6, 3, 7, 12},
{4, 4, 4, 4}};

Output

Identical Matrices

In the above example all the elements in the matrices are same, so they are identical

Time Complexity : O(n^2)

Algorithm

1. For each row in the two matrices, compare the elements in that row,
a. If same, move to the next row else,
b. break, and print “matrices are not identical”
2. If the loop didnt break, then the matrices are identical

C++ Program

#include <bits/stdc++.h>
using namespace std;
#define N 4
int main()
{
	int A[N][N] = { {1, 4, 7, 9},
					{1, 6, 7, 6},
					{6, 3, 7, 12},
					{4, 4, 4, 4}};

	int B[N][N] = { {1, 4, 7, 9},
					{1, 6, 7, 6},
					{6, 3, 7, 12},
					{4, 4, 4, 4}};
	
	
	for(int i=0; i <N; i++)
	{
		for(int j=0; j<N; j++)
			{
				if(A[i][j] != B[i][j])
				{
					cout<<"Not identical matrices\n";
					return 0;
				}
			}
	}
	
	cout<<"Identical matrices\n";
	return 0;
}

Try It

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions