tutorialcup@gmail.com

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


C++ Online Test - Check Your Rank across the World


Next >
Scroll to Top