Computer Applications

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:

43010
10020
10100
03200

Number of zero elements = 11
Number of non zero elements = 9
Matrix is a Sparse Matrix

Java

Java Arrays

2 Likes

Answer

import java.util.Scanner;

class SparseMatrix
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        int a[][] = new int[4][5];
        int i, j, zero = 0, nonzero = 0;

        for(i = 0; i < 4; i++)
        {
            for(j = 0; j < 5; j++)
            {
                System.out.print("Enter element: ");
                a[i][j] = sc.nextInt();
            }
        }

        for(i = 0; i < 4; i++)
        {
            for(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");
    }
}

Output

Answered By

1 Like


Related Questions