Java program to check if it is a sparse matrix

Let’s learn java program to check if it is a sparse matrix.

Java program to check if it is a sparse matrix

Sparse matrix means a matrix having more 0 elements than number of non-zero elements. For example.

java program to check if it is a sparse matrix

Algorithm to check if it is sparse matrix,

  • In java sparse matrix first declare and initialize two dimensional array and count number of rows and columns.
  • Two “for loop” loops through given array and gets the total number of zeroes and stores in variable “total”.
  • In the next step find size of the array.
  • Now if the total is greater than size/2 it is a sparse matrix else it’s not a sparse matrix.

Now let’s see java program to determine whether a given matrix is a sparse matrix.

import java.util;
public class SparseMatrix
{
   public static void main(String[] args)
   {
      int rows, columns, size, total = 0;
      int[][] sparseArray = {     
                 {6, 0, 0},  
                 {0, 9, 0},  
                 {0, 0, 4}  
             };            
      // calculating number of rows and columns  
      rows = sparseArray.length;  
      columns = sparseArray[0].length;            
      // calculating size of array  
      size = rows * columns;            
      // counting zero elements  
      for(int a = 0; a < rows; a++)
      {
         for(int b = 0; b < columns; b++)
         {
            if(sparseArray[a][b] == 0)
            {
               total++;
            }
         }
      }
      if(total > (size/2))
      {
         System.out.println("It's a sparse matrix");
      }
      else
      {
         System.out.println("Not a sparse matrix");
      }
   }
}


Output:

It’s a sparse matrix


Also read – interface in java

Also read – abstraction in java

Also read – nested classes in java

Also read – polymorphism in java