5.Program to determine whether two matrices are equal
💡Code:
import java.util.Scanner; public class EqualMatrices { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Get the dimensions of the matrices from the user System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int columns = scanner.nextInt(); // Create the first matrix int[][] matrix1 = new int[rows][columns]; System.out.println("Enter elements for the first matrix:"); inputMatrix(matrix1, scanner); // Create the second matrix int[][] matrix2 = new int[rows][columns]; System.out.println("Enter elements for the second matrix:"); inputMatrix(matrix2, scanner); // Check if the matrices are equal boolean areEqual = areMatricesEqual(matrix1, matrix2); // Display the result if (areEqual) { System.out.println("The matrices are equal."); } else { System.out.println("The matrices are not equal."); } // Close the scanner scanner.close(); } // Function to input elements into a matrix private static void inputMatrix(int[][] matrix, Scanner scanner) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: "); matrix[i][j] = scanner.nextInt(); } } } // Function to check if two matrices are equal private static boolean areMatricesEqual(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (matrix1[i][j] != matrix2[i][j]) { return false; // Matrices are not equal } } } return true; // Matrices are equal } }
📸Output :
.png)