C Program to Check if Two Matrices Are Equal

Two matrices are equal if and only if they have the same dimensions (same number of rows and same number of columns) and every corresponding pair of elements is equal: A[i][j] == B[i][j] for all i, j. If the dimensions differ, equality is impossible. This program checks both conditions. The original had void main(), exit(1) for dimension mismatch, broken \n, and a nested-loop exit bug: the inner break only exited the inner loop, leaving the outer loop to continue iterating even after a mismatch was found.

Equality Check — Logic Flow

Step Check Result
1 r1 == r2 AND c1 == c2? If No → not equal (different shape)
2 For each (i,j): A[i][j] == B[i][j]? If any mismatch → not equal; exit both loops
3 All elements matched Equal

C Program: Check if Two Matrices Are Equal

/* Check whether two matrices are equal
 * Compile: gcc -ansi -Wall -Wextra matequal.c -o matequal */
#include <stdio.h>
#define MAX 10

void print_matrix(int a[][MAX], int r, int c, const char *label)
{
    int i, j;
    printf("%s:\n", label);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++)
            printf("%4d", a[i][j]);
        printf("\n");
    }
}

int main(void)
{
    int A[MAX][MAX], B[MAX][MAX];
    int i, j, r1, c1, r2, c2, equal;

    printf("Enter order of matrix A (rows cols): ");
    if (scanf("%d %d", &r1, &c1) != 2 || r1<1||r1>MAX||c1<1||c1>MAX) {
        printf("Invalid dimensions.\n"); return 1;
    }
    printf("Enter order of matrix B (rows cols): ");
    if (scanf("%d %d", &r2, &c2) != 2 || r2<1||r2>MAX||c2<1||c2>MAX) {
        printf("Invalid dimensions.\n"); return 1;
    }

    printf("Enter elements of A (%dx%d):\n", r1, c1);
    for (i = 0; i < r1; i++)
        for (j = 0; j < c1; j++)
            if (scanf("%d", &A[i][j]) != 1) { printf("Invalid.\n"); return 1; }

    printf("Enter elements of B (%dx%d):\n", r2, c2);
    for (i = 0; i < r2; i++)
        for (j = 0; j < c2; j++)
            if (scanf("%d", &B[i][j]) != 1) { printf("Invalid.\n"); return 1; }

    print_matrix(A, r1, c1, "Matrix A");
    print_matrix(B, r2, c2, "Matrix B");

    if (r1 != r2 || c1 != c2) {
        printf("Matrices have different dimensions — cannot be equal.\n");
        return 0;
    }

    equal = 1;
    for (i = 0; i < r1 && equal; i++)     /* outer also exits on mismatch */
        for (j = 0; j < c1; j++)
            if (A[i][j] != B[i][j]) { equal = 0; break; }

    if (equal)
        printf("The two matrices are EQUAL.\n");
    else
        printf("The two matrices are NOT equal.\n");

    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra matequal.c -o matequal
./matequal

Sample Output

Enter order of matrix A (rows cols): 2 2
Enter order of matrix B (rows cols): 2 2
Enter elements of A (2x2):
1 2
3 4
Enter elements of B (2x2):
1 2
3 4
Matrix A:
   1   2
   3   4
Matrix B:
   1   2
   3   4
The two matrices are EQUAL.

Enter order of matrix A (rows cols): 2 2
Enter order of matrix B (rows cols): 2 3
...
Matrices have different dimensions — cannot be equal.

Code Explanation

  • Dimension check before element check — checking r1 != r2 || c1 != c2 first avoids undefined behavior from comparing elements with different index bounds. The dimension check is O(1); element comparison is O(r×c). Always do the cheap check first.
  • Nested loop early exit: for (i = 0; i < r1 && equal; i++) — the outer loop condition includes && equal. When equal = 0 is set inside the inner loop and break exits the inner loop, the outer loop’s condition is checked and it also stops. The original program only had break in the inner loop, which only exits that loop — the outer loop continued, doing unnecessary comparisons (but still arriving at the correct answer).
  • return 0 not exit(1) for dimension mismatch — the original used exit(1) from <stdlib.h> to exit when dimensions differ. Using return 0 from main is cleaner and doesn’t require <stdlib.h>. Non-zero exit codes conventionally mean error; a dimension mismatch is a valid result, not an error, so return 0 is appropriate.
  • print_matrix helper function — extracting the 2D print loop into a function avoids repeating the same nested loop three times (for A, B, and the result). Functions that accept a 2D array in C require specifying all dimensions except the first in the parameter: int a[][MAX].

What This Program Teaches

  • Exiting nested loops — C has no labeled break. The standard patterns for early exit from nested loops are: (1) use a flag variable in all loop conditions, (2) use goto (acceptable for this specific pattern), (3) extract the inner loops into a function and use return. The flag pattern used here is the most common in C89-compatible code.
  • Matrix identity vs equality — two matrices being equal (same values) is different from being the same matrix in memory (same pointer). In C, A == B for arrays compares pointer values, not contents. Always compare elements explicitly.
  • Dimension validation — reading dimensions from user input and checking them against array bounds prevents buffer overflow. Without the check, scanf into A[r1][c1] with r1=100 would write past the end of the array.

Related Programs

Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
 | 
C Programming: A Modern Approach — K.N. King (India) |
(US)

Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>