JAVA SP T


Lets dive into snapshot of my programs!💻

13. Program to determine whether a given matrix is a sparse matrix

💡Code:

 import java.util.Scanner;

              public class SparseMatrixCheck7078 {
                  public static void main(String[] args) {
                      Scanner scanner = new Scanner(System.in);
              
                      // Get the dimensions of the matrix 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 matrix
                      int[][] matrix = new int[rows][columns];
                      System.out.println("Enter elements for the matrix:");
                      inputMatrix(matrix, scanner);
              
                      // Check if the matrix is sparse
                      boolean isSparseMatrix7078 = checkSparseMatrix7078(matrix);
              
                      // Display the result
                      if (isSparseMatrix7078) {
                          System.out.println("The given matrix is a Sparse Matrix.");
                      } else {
                          System.out.println("The given matrix is not a Sparse Matrix.");
                      }
              
                      // 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 a matrix is sparse
                  private static boolean checkSparseMatrix7078(int[][] matrix) {
                      int rows = matrix.length;
                      int columns = matrix[0].length;
              
                      // Count the number of zero elements in the matrix
                      int zeroCount = 0;
                      for (int i = 0; i < rows; i++) {
                          for (int j = 0; j < columns; j++) {
                              if (matrix[i][j] == 0) {
                                  zeroCount++;
                              }
                          }
                      }
              
                      // Determine if the matrix is sparse based on the zero count
                      return zeroCount > (rows * columns) / 2;
                  }
              }
               

📸Output :

output