Java Program to Determine if a given 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.

advertisement
  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

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

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn