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.

import java.util.Scanner;

public class Sparse

`{`

public static void main(String args[])

`{`

int i, j, zero = 0, count = 0;

int array[][] = new int[10][10];

System.out.println("Enter total rows and columns: ");

Scanner s = new Scanner(System.in);

int row = s.nextInt();

int column = s.nextInt();

System.out.println("Enter matrix:");

for(i = 0; i < row; i++)

`{`

for(j = 0; j < column; j++)

`{`

array[i][j] = s.nextInt();

System.out.print(" ");

`}`

`}`

for(i = 0; i < row; i++)

`{`

for(j = 0; j < column; j++)

`{`

if(array[i][j] == 0)

`{`

`zero++;`

`}`

`else`

`{`

`count++;`

`}`

`}`

`}`

if(zero>count)

`{`

System.out.println("the matrix is sparse matrix");

`}`

`else`

`{`

System.out.println("the matrix is not a sparse matrix");

`}`

`}`

`}`

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.**

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

advertisement

advertisement

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

**Next Steps:**

- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Practice BCA MCQs
- Buy Programming Books
- Apply for Java Internship
- Buy Java Books
- Practice Programming MCQs