**C++ program to check the equality of two matrices** has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered to be equal if both of the following conditions are satisfied

(i) Number of rows and columns are same for both of the matrices i.e. $m = p$ and $n = q$

(ii) Each elements of $A$ is equal to corresponding element of $B$ i.e. $A_{ij} = B_{xy}$ for each $i \in m$, $j \in n$, $x \in p$, $y \in q$, $i = x$ and $j = y$.

## 1. C++ Program to check the equality of two matrices

/******************************************** alphabetacoder.com C++ program to check equality of two matrices *********************************************/ #include <iostream> using namespace std; int main() { int m, n, p, q, flag = 0, i, j; int A[10][10] = {0}, B[10][10] = {0}; //take input of the order of first matrix cout << "Enter the number of row and column of first matrix="; cin >> m; cin >> n; //take input of the first matrix cout << "Enter the first matrix of order " << m << " x " << n << " = \n"; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cin >> A[i][j]; } } //take input of the order of second matrix cout << "Enter the number of row and column of second matrix="; cin >> p; cin >> q; //take input of the first matrix cout << "Enter the first matrix of order " << p << " x " << q << " = \n"; for (i = 0; i < p; i++) { for (j = 0; j < q; j++) { cin >> B[i][j]; } } // check if order of matrices are same // if not same order then check each corresponding elements if (m != p || n != q) { cout << "\nMatrices are of different order,hence not equal"; flag = 1; } else { //check equality of each corresponding elements for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (A[i][j] != B[i][j]) { // inequality spotted cout << "\nMatrices are not equal. Element mismatch at " << i + 1 << " row " << j + 1 << " column"; flag = 1; break; } } if (flag == 1) break; } } if (flag == 0) cout << "\nMatrices are equal"; return 0; }

Output

**Case 1:**

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

1 2 3

4 5 6

7 8 9

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

8 0 5

6 4 1

Matrices are of different order,hence not equal

**Case 2:**

Enter the number of row and column of first matrix=2 2

Enter the first matrix of order 2 x 2=

1 2

4 5

Enter the number of row and column of second matrix=2 2

Enter the second matrix of order 2 x 2=

1 2

4 5

Matrices are equal

**Case 3:**

Enter the number of row and column of first matrix=2 2

Enter the first matrix of order 2 x 2=

1 3

5 6

Enter the number of row and column of second matrix=2 2

Enter the second matrix of order 2 x 2=

1 3

5 7

Matrices are not equal. Element mismatch at 2 row 2 column

## No comments:

## Post a Comment

If you have any doubts or suggestions, please leave a note.