Hey guys!! Welcome to flower brackets blog. In this post we are going learn java program to check sparse matrix.

#### Java program to check sparse matrix

- In this java program first user enters the dimensions of matrix. That is, number of rows and columns.
- This is stored in variables “x” and “y”. (x * y) / 2 formula is used check the threshold.
- Sparse matrix has more zero elements. If given matrix contains more than (x * y) / 2 of zeros then, it is sparse matrix else it’s not.

Also read – Sparse matrix representation

import java.util.Scanner;

public class SparseMatrix

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

System.out.println("Please enter dimensions of matrix : ");

int x = sc.nextInt();

int y = sc.nextInt();

double givenMatrix[][] = new double[x][y];

int checkZero = 0;

System.out.println("Please enter elements of matrix : ");

for(int a = 0; a < x; a++)

{

for(int b = 0; b < y; b++)

{

givenMatrix[a][b] = sc.nextDouble();

if(givenMatrix[a][b] == 0)

{

checkZero++;

}

}

}

if(checkZero > (x * y) / 2)

{

System.out.println("It is a sparse matrix!!!");

}

else

{

System.out.println("It is not a sparse matrix.");

}

sc.close();

}

}

**Output:**