Java program to check if it is a sparse matrix

In this post we are going learn java sparse matrix or java program to check if it is a sparse matrix.

Sparse matrix java means a matrix having more 0 elements. For example,

Java program to check if it is a 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 a program to determine whether a given matrix is a sparse matrix,

// java sparse matrix
import java.util;

public class SparseMatrix
{
public static void main(String[] args)
{
int rows, columns, size, total = 0;
int arrNumber[][] = {
{6, 0, 0},
{0, 9, 0},
{0, 0, 4}
};
// calculating number of rows and columns
rows = arrNumber.length;
columns = arrNumber.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(arrNumber[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