# JAVA PROGRAM TO IDENTIFY A SPARSE MATRIX

Here in this particular tutorial, we are going to see how to check if a matrix is a sparse matrix or not. To do this, we have included the Scanner class and also some of the looping statements.

## Implementation of the Java Code :

Generally, a matrix is said to be a 2-D array that has 'm' no. of columns and 'n' no. of rows which give us m*n matrix. Sparse matrices are the matrices that have the most of their elements are zero. So, a sparse matrix is nothing but a matrix that has more zero elements than the non zero elements.

To implement this java code first, we need to take the input from the user. Then, we need to calculate several rows and columns present in the given matrix. Also, calculate the size of the array. Then, we will count all zero elements present in the matrix. If the zero elements are more than the non-zero elements, then we will print "Given matrix is a sparse matrix". If the zero elements are less than the non-zero elements, then we will print "Given matrix is not a sparse matrix".

In this way, we will identify whether a given matrix is a sparse matrix or not.

```import java.util.*;
public class Main
{
public static void main(String[] args) {
int rows, cols, size, count = 0;

int m, n, c, d;
Scanner scan = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix :");
m = scan.nextInt();
n = scan.nextInt();

int matrix[][] = new int[m][n];
System.out.println("Enter the elements of matrix :");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
matrix[c][d] = scan.nextInt();
}
}

//Calculates number of rows and columns present in given matrix
rows = matrix.length;
cols = matrix[0].length;

//Calculates the size of array
size = rows * cols;

//Count all zero element present in matrix
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(matrix[i][j] == 0)
count++;
}
}

if(count > (size/2))
{
System.out.println("Given matrix is a sparse matrix");
}
else
{
System.out.println("Given matrix is not a sparse matrix");
}
}
}```

OUTPUT 1 :  If given matrix is not a Sparse Matrix.

OUTPUT 2 :  If given matrix is a Sparse Matrix.

Submitted by BODA KAVYA SREE (Kavyasree1903)