Advertisements
Advertisements
प्रश्न
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 a sparse, if the total number of zero elements is greater than the total number of non-zero elements. Print appropriate messages.
Example:

कोड लेखन
Advertisements
उत्तर
import java.util.Scanner;
public class SparseMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Declare a 2D array of order 4x5
int[][] matrix = new int[4][5];
int zeroCount = 0;
int nonZeroCount = 0;
// Input: Accepting elements for the matrix
System.out.println("Enter 20 elements for a 4x5 matrix:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
matrix[i][j] = sc.nextInt();
// Logic: Counting zero and non-zero elements
if (matrix[i][j] == 0) {
zeroCount++;
} else {
nonZeroCount++;
}
}
}
// Output: Printing the counts
System.out.println("Number of zero elements = " + zeroCount);
System.out.println("Number of non zero elements = " + nonZeroCount);
// Condition check for Sparse Matrix
if (zeroCount > nonZeroCount) {
System.out.println("Matrix is a Sparse Matrix");
} else {
System.out.println("Matrix is NOT a Sparse Matrix");
}
}
}
shaalaa.com
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
