C Program to Check Whether Two Matrices Are Equal or Not
Last Updated :
02 Aug, 2022
Here, we will see how to check whether two matrices are equal or not using a C Program
Input:
First Matrix:
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
Second matrix:
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
Output:
Matrices are equal.
Approach:
For any two matrices to be equal, the number of rows and columns in both the matrices should be equal and the corresponding elements also equal.
Example:
C
#include <stdio.h>
#define N 4 // Macros
int areSame( 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] = { { 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 } };
int B[N][N] = { { 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 } };
printf ( "\n First Matrix \n" );
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
printf ( " %d" , A[i][j]);
}
printf ( "\n" );
}
printf ( "\n Second Matrix \n" );
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
printf ( " %d" , B[i][j]);
}
printf ( "\n" );
}
if (areSame(A, B))
printf ( "\n Matrices are equal" );
else
printf ( "\n Matrices are not equal" );
return 0;
}
|
Output
First Matrix
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Second Matrix
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Matrices are equal
Time complexity: O(n2).
Auxiliary space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...