Javatpoint Logo
Javatpoint Logo

Program to determine whether a given matrix is a sparse matrix

Explanation

In this program, we need to check whether the given matrix is the sparse matrix.

Sparse Matrix

A matrix is said to be sparse matrix if most of the elements of that matrix are 0. It implies that it contains very less non-zero elements.

To check whether the given matrix is the sparse matrix or not, we first count the number of zero elements present in the matrix. Then calculate the size of the matrix. For the matrix to be sparse, count of zero elements present in an array must be greater than size/2.

Program to determine whether a given matrix is a sparse matrix

Number of zeroes present in above matrix is 6 and size of the matrix is 3 * 3 = 9. Since, 6 > 4.5 that means, most elements of given array are zero. Hence, the above matrix is a sparse matrix.

Algorithm

  1. Declare and initialize a two-dimensional array a.
  2. Calculate the number of rows and columns present in the given array and store it in variables rows and cols respectively.
  3. Loop through the array and count the number of zeroes present in the given array and store in the variable count.
  4. Calculate the size of the array by multiplying the number of rows with many columns of the array.
  5. If the count is greater than size/2, given matrix is the sparse matrix. That means, most of the elements of the array are zeroes.
  6. Else, the matrix is not a sparse matrix.

Solution

Python

Output:

Given matrix is a sparse matrix

C

Output:

Given matrix is a sparse matrix

JAVA

Output:

Given matrix is a sparse matrix

C#

Output:

Given matrix is a sparse matrix

PHP

Output:

Given matrix is a sparse matrix

Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials