Friday, 17 November 2017

Java Program to Check if it is a Sparse Matrix


Code:

import java.util.Scanner;

public class Sparsity_Matrix 
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the dimensions of the matrix: ");
        int m = sc.nextInt();
        int n = sc.nextInt();
        double[][] mat = new double[m][n];
        int zeros = 0;
        System.out.println("Enter the elements of the matrix: ");
        for(int i=0; i
        {
            for(int j=0; j
            {
                mat[i][j] = sc.nextDouble();
                if(mat[i][j] == 0)
                {
                    zeros++;
                }
            }
        }

        if(zeros > (m*n)/2)
        {
            System.out.println("The matrix is a sparse matrix");
        }
        else
        {
            System.out.println("The matrix is not a sparse matrix");
        }

        sc.close();
    }
}


Output:

Enter the dimensions of the matrix: 
2 3
Enter the elements of the matrix: 
1 0 0
2 1 1
The matrix is not a sparse matrix


More Java Programs:












100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...