Open In App

C Program to Check Whether Two Matrices Are Equal or Not

Last Updated : 02 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C Program to check if two matrices are equals or not
#include <stdio.h>
#define N 4 // Macros
  
// This function returns 1 if A[][] and B[][] are equal
// otherwise it returns 0
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;
}
  
// driver code
int main()
{
  
    // create two matrices
    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 } };
  
    // Display first matrix
    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");
    }
  
    // Display second matrix
    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");
    }
  
    // check if Matrices are equals or not
    // areSame(A, B) function accept two matrices as input
    // and return 1 if matrices are equals otherwise return
    // 0
    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
Previous
Next
Share your thoughts in the comments

Similar Reads