Java program to check if two given matrices are identical


Two matrices are identical if their number of rows and columns are equal and the corresponding elements are also equal. An example of this is given as follows.

Matrix A =
1 2 3
4 5 6
7 8 9
Matrix B =
1 2 3
4 5 6
7 8 9
The matrices A and B are identical

A program that checks if two matrices are identical is given as follows.

Example

 Live Demo

public class Example {
   public static void main (String[] args) {
      int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
      int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
      int flag = 1;
      int n = 3;
      for (int i = 0; i < n; i++)
         for (int j = 0; j < n; j++)
            if (A[i][j] != B[i][j])
               flag = 0;
            if (flag == 1)
               System.out.print("Both the matrices are identical");
            else
               System.out.print("Both the matrices are not identical");
   }
}

Output

Both the matrices are identical

Now let us understand the above program.

The two matrices A and B are defined. The initial value of flag is 1. Then a nested for loop is used to compare each element of the two matrices. If any corresponding element is not equal, then value of flag is set to 0. The code snippet that demonstrates this is given as follows −

int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int flag = 1;
int n = 3;
for (int i = 0; i < n; i++)
   for (int j = 0; j < n; j++)
      if (A[i][j] != B[i][j])
   flag = 0;

If flag is 1, then matrices are identical and this is displayed. Otherwise, the matrices are not identical and this is displayed. The code snippet that demonstrates this is given as follows −

if (flag == 1)
   System.out.print("Both the matrices are identical");
else
   System.out.print("Both the matrices are not identical");

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

937 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements