Example:
If matrix 1 =
1 2 3
4 5 6
7 8 9
And matrix 2 =
1 2 3
4 5 6
7 8 9
Output: Both matrices are equal.
Required knowledge:
Basic C programming, For loop, Array, MatrixEquality of matrix
Checking whether two matrices are equal or not is very simple and fundamental. Two matrices are said to be equal if and only if they are of same size and they have equal corresponding entries.Equality of two matrices A and B can be defined as
Aij = Bij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n).
Both the matrices are of same dimension and also their corresponding elements are equal. Hence both Matrix A and Matrix B are equal.
Program:
/** * C program to check whether two matrices are equal or not */ #include <stdio.h> int main() { int A[3][3], B[3][3]; int row, col, isEqual; /* * Reads elements in first matrix from user */ printf("Enter elements in matrix A of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &A[row][col]); } } /* * Reads elements in second matrix from user */ printf("\nEnter elements in matrix B of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &B[row][col]); } } /* Assumes that the matrices are equal */ isEqual = 1; for(row=0; row<3; row++) { for(col=0; col<3; col++) { /* * If the corresponding entries of matrices are not equal */ if(A[row][col] != B[row][col]) { isEqual = 0; break; } } } /* * Checks the value of isEqual * As per our assumption if isEqual contains 1 means both are equal * If it contains 0 means both are not equal */ if(isEqual == 1) { printf("\nMatrix A is equal to Matrix B"); } else { printf("\nMatrix A is not equal to Matrix B"); } return 0; }
Output
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9
Enter elements in matrix B of size 3x3:
1 2 3
4 -5 6
7 8 9
Matrix A is not equal to Matrix B
1 2 3
4 5 6
7 8 9
Enter elements in matrix B of size 3x3:
1 2 3
4 -5 6
7 8 9
Matrix A is not equal to Matrix B
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to check Identity matrix.
- C program to check Sparse matrix.
- C program to check Symmetric matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.
- C program to copy elements of array.
- C program to count total number of duplicate elements in an array.
- C program to count total number of negative elements in an array.
- C program to count frequency of each elements in an array.
- C program to find all unique elements in an array.
- C program to find power of any number without using pow() function.
- C program to find sum of first and last digit of any number.
- C program to create Simple Calculator using switch case.