📊Beginner

Check Whether Two Matrices Are Equal

Compare two matrices

Check if two matrices are equal by comparing corresponding elements.

Program Code

matrix_equal.c
C
1#include <stdio.h>
2#include <stdbool.h>
3
4bool areMatricesEqual(int A[][3], int B[][3], int rows, int cols) {
5 for (int i = 0; i < rows; i++) {
6 for (int j = 0; j < cols; j++) {
7 if (A[i][j] != B[i][j]) {
8 return false;
9 }
10 }
11 }
12 return true;
13}
14
15int main() {
16 int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
17 int B[2][3] = {{1, 2, 3}, {4, 5, 6}};
18 int C[2][3] = {{1, 2, 3}, {4, 5, 7}};
19
20 printf("Matrix A:\n");
21 for (int i = 0; i < 2; i++) {
22 for (int j = 0; j < 3; j++)
23 printf("%d ", A[i][j]);
24 printf("\n");
25 }
26
27 printf("\nMatrix B:\n");
28 for (int i = 0; i < 2; i++) {
29 for (int j = 0; j < 3; j++)
30 printf("%d ", B[i][j]);
31 printf("\n");
32 }
33
34 printf("\nA and B are %s\n",
35 areMatricesEqual(A, B, 2, 3) ? "EQUAL" : "NOT EQUAL");
36 printf("A and C are %s\n",
37 areMatricesEqual(A, C, 2, 3) ? "EQUAL" : "NOT EQUAL");
38
39 return 0;
40}
Output

Matrix A:

1 2 3

4 5 6

 

Matrix B:

1 2 3

4 5 6

 

A and B are EQUAL

A and C are NOT EQUAL