Home »
Java Programs »
Java Array Programs
Java program to check sparse matrix
In this java program, we are going to read a matrix and check whether it is sparse matrix or not?
By IncludeHelp Last updated : December 23, 2023
Problem statement
Given a matrix and we have to check whether it is sparse matrix or not using java program.
Sparse Matrix
A matrix in which most of the elements are '0' then it is said to be a sparse matrix. Sparse matrices are used in specific ways in computer science and have different storage and techniques related to their use.
Sparse Matrix Examples
Example-1
Input Matrix
1 1 1
0 0 0
1 1 1
Output: It's not a sparse matrix
Example-2
Input Matrix
1 0 0 1
0 1 0 1
0 1 0 1
0 0 0 1
Output: It's a sparse matrix
Java program to check sparse matrix
import java.util.Scanner;
public class MatrixSparse {
public static void main(String args[]) {
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input numbers of rows and cols
System.out.print("Enter the dimensions of the matrix : ");
int m = sc.nextInt();
int n = sc.nextInt();
//declare two_d array (matrix) object
double[][] mat = new double[m][n];
//variable to store zero count
//initializing it with 0
int zeros = 0;
//input matrix
System.out.println("Enter the elements of the matrix : ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextDouble();
if (mat[i][j] == 0) {
//counting zeros
zeros++;
}
}
}
//check condiion
if (zeros > (m * n) / 2) {
System.out.println("The matrix is a sparse matrix");
} else {
System.out.println("The matrix is not a sparse matrix");
}
sc.close();
}
}
Output 1
Enter the dimensions of the matrix : 3 3
Enter the elements of the matrix :
1 1 1
0 0 0
1 1 1
The matrix is not a sparse matrix
Output 2
Enter the dimensions of the matrix : 4 4
Enter the elements of the matrix :
1 0 0 1
0 1 0 1
0 1 0 1
0 0 0 1
The matrix is a sparse matrix
Java Array Programs »