C program to check sparse matrix

Write a C program to read elements in a matrix and check whether matrix is Sparse matrix or not. C program for determining sparse matrix. How to check sparse matrix in C.

Example: If elements of the matrix is:
1 0 3
0 0 4
6 0 0
Output: Sparse matrix

Required knowledge:

Basic C programming, Fop loop, Array, Matrix

Sparse matrix:

Sparse matrix is a special matrix with most of its elements are zero. We can also assume that if (m * n) / 2 elements are zero then it is a sparse matrix.

Algorithm to check sparse matrix:

To check whether a matrix is sparse matrix we only need to check the total number of elements that are equal to zero.

If total number of elements equal to zero is defined by T then
T ≥ ((m * n) / 2 )
Sparse matrix

Program:

/**
 * C program to check sparse matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3];
    int row, col, total=0;

    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Counts total number of zero elements in the matrix
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /*
             * If the current element is zero
             */
            if(A[row][col] == 0)
            {
                total++;
            }
        }
    }

    if(total >= (row * col)/2)
    {
        printf("\nThe given matrix is a Sparse matrix.");
    }
    else
    {
        printf("\nThe given matrix is not Sparse matrix.");
    }

    return 0;
} 
Output
X
_
Enter elements in matrix of size 3x3:
1 0 0
4 5 0
0 0 0

The given matrix is a Sparse matrix.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment