JAVA SP T


Lets dive into snapshot of my programs!💻

11. Program to determine whether a given matrix is an identity matrix

💡Code:

import java.util.Scanner;

              public class IdentityMatrixCheck7078 {
                  public static void main(String[] args) {
                      Scanner scanner = new Scanner(System.in);
              
                      // Get the order of the square matrix from the user
                      System.out.print("Enter the order of the square matrix: ");
                      int order = scanner.nextInt();
              
                      // Create the matrix
                      int[][] matrix = new int[order][order];
                      System.out.println("Enter elements for the matrix:");
                      inputMatrix(matrix, scanner);
              
                      // Check if the matrix is an identity matrix
                      boolean isIdentityMatrix = checkIdentityMatrix(matrix);
              
                      // Display the result
                      if (isIdentityMatrix) {
                          System.out.println("The given matrix is an Identity Matrix.");
                      } else {
                          System.out.println("The given matrix is not an Identity Matrix.");
                      }
              
                      // Close the scanner
                      scanner.close();
                  }
              
                  // Function to input elements into a square 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 a matrix is an identity matrix
                  private static boolean checkIdentityMatrix(int[][] matrix) {
                      int rows = matrix.length;
                      int columns = matrix[0].length;
              
                      // Check if the matrix is square
                      if (rows != columns) {
                          return false;
                      }
              
                      // Check if the diagonal elements are 1 and the rest are 0
                      for (int i = 0; i < rows; i++) {
                          for (int j = 0; j < columns; j++) {
                              if ((i == j && matrix[i][j] != 1) || (i != j && matrix[i][j] != 0)) {
                                  return false;
                              }
                          }
                      }
              
                      return true;
                  }
              }
              

📸Output :

output