Java Program to Check if a Matrix is a Sparse Matrix

This is a Java Program to Determine if a given Matrix is a Sparse Matrix. If the number of zero elements are more than the non-zero elements of the matrix then it is known as Sparse Matrix

Enter the elements of array as input. Now we use loops and if else condition to check for Sparse Matrix.

Here is the source code of the Java Program to Determine if a given Matrix is a Sparse Matrix. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Sparse
  3. {
  4.     public static void main(String args[])
  5.     {
  6.  	int i, j, zero = 0, count = 0; 
  7.  	int array[][] = new int[10][10];
  8.  	System.out.println("Enter total rows and columns: ");
  9.  	Scanner s = new Scanner(System.in);
  10.  	int row = s.nextInt();
  11.  	int column = s.nextInt();
  12.  	System.out.println("Enter matrix:");
  13.         for(i = 0; i < row; i++)
  14.         {
  15.             for(j = 0; j < column; j++) 
  16.     	    {
  17.                  array[i][j] = s.nextInt();
  18.                  System.out.print(" ");
  19.     	     }
  20.         }
  21.         for(i = 0; i < row; i++)
  22.         {
  23.  	    for(j = 0; j < column; j++) 
  24.   	    {
  25.                 if(array[i][j] == 0)
  26.     		{
  27.         	    zero++; 
  28.     		}
  29.     	   	else
  30.             	{
  31.       	            count++;
  32.     	    	}
  33.    	   }
  34.        }
  35.        if(zero>count)
  36.        {
  37.            System.out.println("the matrix is sparse matrix");
  38.        }
  39.        else
  40.        {
  41.            System.out.println("the matrix is not a sparse matrix");
  42.        }
  43.     }
  44. }

Output:

$ javac Sparse.java
$ java Sparse 
 
Enter total rows and columns: 
3
3
Enter matrix:
1
0
5
0
0
8
0
0
0
the matrix is sparse matrix

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.