
Write a program to accept a two-dimensional integer array of order 4 x 5 as input from the user. Check if it is a Sparse Matrix or not. A matrix is considered to be sparse if the total number of zero elements is greater than the total number of non-zero elements. Print appropriate messages. Example: 4 3 0 1 0 1 0 0 2 0 1 0 1 0 0 0 3 2 0 0 Number of zero elements = 11 Number of non zero elements = 9 Matrix is a Sparse Matrix
Topic: Two-dimensional array — Sparse Matrix
Answer
import java.util.Scanner;
class Sparse { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[][] = new int[4][5]; int zero = 0, nonzero = 0;
System.out.println("Enter 20 elements of the 4 x 5 array :"); for(int i = 0; i < 4; i++) for(int j = 0; j < 5; j++) a[i][j] = sc.nextInt();
for(int i = 0; i < 4; i++) { for(int j = 0; j < 5; j++) { if(a[i][j] == 0) zero++; else nonzero++; } }
System.out.println("Number of zero elements = " + zero); System.out.println("Number of non zero elements = " + nonzero);
if(zero > nonzero) System.out.println("Matrix is a Sparse Matrix"); else System.out.println("Matrix is not a Sparse Matrix"); } }
The same nested-loop skeleton as every 2-D array question — outer loop for rows, inner loop for columns — with a simple test in the middle.
Order matters in the declaration: new int[4][5] means 4 rows and 5 columns, so the outer loop runs to 4 and the inner to 5. Writing them the wrong way round is the usual slip, and with a non-square matrix it causes an ArrayIndexOutOfBoundsException rather than a quietly wrong answer.
Only one counter is strictly necessary — the non-zero count is simply 20 minus the zeros — but keeping both makes the logic obvious and costs nothing.
Read the definition precisely: sparse means zeros are GREATER than non-zeros, not greater than or equal. A matrix with 10 of each is therefore not sparse.
Check with the sample: 11 zeros against 9 non-zeros, so 11 > 9 and the matrix is sparse, exactly as the question states.
a[][] int[4][5] - stores the 20 elements entered by the user zero int - counter for the zero elements nonzero int - counter for the non-zero elements i, j int - loop variables for rows and columns sc Scanner - object used to read input