Check If Two Matrices Are Identical in Java



Problem Statement

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.

Input

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

Output

Both the matrices are identical

Steps to check if two given matrices are identical

Following are the steps to check if two given matrices are identical ?

  • Initialize two matrices by defining two 2D arrays to represent the matrices.
  • Set up a flag by using a variable (e.g., flag) to track if the matrices are identical. Initially, set it to 1 (true).
  • Loop through elements by using nested loops to iterate through each element of both matrices. Compare corresponding elements.
  • Check the elements if any pair of elements in the two matrices are different, set the flag to 0 (false).
  • After the loops, if the flag is still 1, print that the matrices are identical. Otherwise, print that they are not.

Java program to check if two given matrices are identical

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

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

Code Explanation

Now let us understand the above program.

The two matrices A and B are defined. The initial value of the 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 the value of the 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 the 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");/pre>
Updated on: 2024-09-20T21:39:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements