Home >>Java Programs >Java Program to Check if it is a Sparse Matrix
In this example, we will create a java program to check whether the given matrix is a sparse matrix.
Any given matrix is said to be a sparse matrix if most of the elements of that matrix are 0. It means that it contains very less non-zero elements.
public class Main
{
public static void main(String[] args)
{
int rows, cols, size, count = 0;
int a[][] =
{
{2, 0, 0},
{0, 3, 0},
{1, 0, 6}
};
rows = a.length;
cols = a[0].length;
size = rows * cols;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
if(a[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");
}
}