Sparse Matrix Check

This program checks if a matrix is sparse.

Problem Statement

Write a Java program to check whether a 3x3 matrix is sparse (more zeros than non zeros).

Source Code

1 public class SparseMatrixCheck {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Sparse Matrix Check");
4 int[][] A = {{0,0,3},{0,0,0},{4,0,0}};
5 int zeroCount=0, nonZeroCount=0;
6 for(int i=0;i<3;i++){
7 for(int j=0;j<3;j++){
8 if(A[i][j]==0) zeroCount++;
9 else nonZeroCount++;
10 }
11 }
12 if(zeroCount>nonZeroCount) System.out.println("Matrix is sparse");
13 else System.out.println("Matrix is not sparse");
14 }
15 }

Program Output

Eduinq Sparse Matrix Check
Matrix is sparse

Explanation

A sparse matrix has more zero elements than non-zero ones, so nested loops count zeros and non-zeros separately, and a comparison decides sparsity, demonstrating how multidimensional arrays can be analyzed for sparsity.

Quick Links to Explore