Java program to check sparse matrix

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

Here’s the java program to check if it is a sparse matrix,

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:

java program to check sparse matrix

Related Posts