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

## Java program to check if it is a sparse matrix

write a java program to determine whether a given matrix is a sparse matrix is one of the common interview question.

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

Algorithm to check if it is sparse matrix –

- first user enters the dimensions of two dimensional array and dimensions are stored in two integer variables.
- declare and initialize two dimensional array with dimensions.
- Two “for loops” is used to enter elements of matrix.
- In the next step using if-else check if matrix contains more than (x*y)/2 number of zeros.
- Now if matrix contains more than (x*y)/2 number of zeros it is a sparse matrix else it is 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) { Scanner sc = new Scanner(System.in); System.out.println("Please enter dimensions of sparse matrix: "); int x = sc.nextInt(); int y = sc.nextInt(); int[][] arrNumber = new int[x][y]; int zeros = 0; System.out.println("Please enter elements of sparse matrix: "); for(int a = 0; a < x; a++) { for(int b = 0; b < y; b++) { arrNumber[a][b] = sc.nextInt(); if(arrNumber[a][b] == 0) { zeros++; } } } if(zeros > (x * y) / 2) { System.out.println("Given matrix is sparse matrix."); } else { System.out.println("Given matrix is not a sparse matrix."); } sc.close(); } }

**Output:**

Please enter dimensions of sparse matrix:

3 4

Please enter elements of sparse matrix:

5 0 0 0

0 1 0 0

0 0 3 1

Given matrix is sparse matrix.

Please enter dimensions of sparse matrix:

2 3

Please enter elements of sparse matrix:

3 0 0

5 4 1

Given matrix is not a sparse matrix.

Also read – interface in java

Also read – abstraction in java

Also read – nested classes in java

Also read – polymorphism in java