Q:

Java program to check sparse matrix

belongs to collection: Java Array Programs

0

Given a matrix and we have to check whether it is sparse matrix or not using java program.

Sparse Matrix

A matrix in which most of the elements are '0' then it is said to be a sparse matrix. Sparse matrices are used in specific ways in computer science and have different storage and techniques related to their use.

Example-1

Input Matrix 
1 1 1
0 0 0 
1 1 1

Output: It's not a sparse matrix

Example-2

Input Matrix 
1 0 0 1
0 1 0 1
0 1 0 1
0 0 0 1

Output: It's a sparse matrix 

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to check sparse matrix in Java

import java.util.Scanner;

public class MatrixSparse {
  public static void main(String args[]) {
    //scanner class object creation
    Scanner sc = new Scanner(System.in);

    //input numbers of rows and cols
    System.out.print("Enter the dimensions of the matrix : ");
    int m = sc.nextInt();
    int n = sc.nextInt();

    //declare two_d array (matrix) object
    double[][] mat = new double[m][n];

    //variable to store zero count
    //initializing it with 0
    int zeros = 0;

    //input matrix 
    System.out.println("Enter the elements of the matrix : ");
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        mat[i][j] = sc.nextDouble();
        if (mat[i][j] == 0) {
          //counting zeros
          zeros++;
        }
      }
    }

    //check condiion
    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 1

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

Output 2

Enter the dimensions of the matrix : 4 4
Enter the elements of the matrix : 
1 0 0 1
0 1 0 1
0 1 0 1
0 0 0 1
The matrix is a sparse matrix

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find the common elements in two in... >>
<< Java program to subtract two matrices (subtraction...