Google News
logo
Java Program to determine whether a given matrix is a sparse matrix
In the following examples of Java program to determine whether a given matrix is a sparse matrix :
Program :
public class SparseMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
        int count = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    count++;
                }
            }
        }
        if (count > (matrix.length * matrix[0].length) / 2) {
            System.out.println("The given matrix is a sparse matrix.");
        } else {
            System.out.println("The given matrix is not a sparse matrix.");
        }
    }
}
Output :
The given matrix is a sparse matrix.
In this program, we have a matrix matrix represented as a two-dimensional array. We initialize a variable count to 0.

We use two nested loops to iterate over the elements of the matrix. The outer loop iterates over the rows, and the inner loop iterates over the columns. For each element in the matrix, we check whether it is equal to 0. If it is equal to 0, we increment the count variable.

Finally, we check whether the number of zeros in the matrix is greater than half the number of elements in the matrix. If it is greater than half the number of elements in the matrix, we print that the matrix is a sparse matrix. Otherwise, we print that the matrix is not a sparse matrix.