Java Online Compiler
Example: MatrixEqualityIterative in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// MatrixEqualityIterative public class Main { public static boolean areMatricesEqualIterative(int[][] matrix1, int[][] matrix2) { // Step 1: Check if both matrices are null if (matrix1 == null && matrix2 == null) { return true; } // Step 2: Check if one matrix is null and the other isn't if (matrix1 == null || matrix2 == null) { return false; } // Step 3: Check if the number of rows is the same if (matrix1.length != matrix2.length) { return false; } // Step 4: Check if the number of columns in each row is the same for (int i = 0; i < matrix1.length; i++) { if (matrix1[i].length != matrix2[i].length) { return false; } } // Step 5: Compare each element for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[i].length; j++) { if (matrix1[i][j] != matrix2[i][j]) { return false; // Found a mismatch } } } // Step 6: If all checks pass, matrices are equal return true; } public static void main(String[] args) { int[][] matrixA = {{1, 2, 3}, {4, 5, 6}}; int[][] matrixB = {{1, 2, 3}, {4, 5, 6}}; int[][] matrixC = {{1, 2, 3}, {4, 5, 9}}; // Different element int[][] matrixD = {{1, 2}, {4, 5, 6}}; // Different column count in row System.out.println("Matrix A and Matrix B are equal: " + areMatricesEqualIterative(matrixA, matrixB)); System.out.println("Matrix A and Matrix C are equal: " + areMatricesEqualIterative(matrixA, matrixC)); System.out.println("Matrix A and Matrix D are equal: " + areMatricesEqualIterative(matrixA, matrixD)); } }
Output
Clear
ADVERTISEMENTS