C program to check a given matrix is a sparse matrix or not

Here, we are going to learn how to check whether a given matrix is a sparse matrix or not in C programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

A sparse matrix is a matrix in which most of the elements are zero.

Given a matrix, and we have to check whether the matrix is a sparse matrix or not using C program.

Program:

The source code to check a given matrix is a sparse matrix or not is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check a given matrix is a sparse matrix or not

#include <stdio.h>
#define ROW 3
#define COL 3

int main()
{
    int matrix[ROW][COL];

    int i, j;
    int counter = 0;

    printf("Enter the elements of the matrix:\n");
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j) {
            scanf("%d", &matrix[i][j]);
            if (matrix[i][j] == 0)
                ++counter;
        }
    }

    if (counter > ((ROW * COL) / 2))
        printf("Matrix is a Sparse Matrix\n");
    else
        printf("Matrix is not aa Sparse Matrix\n");

    return 0;
}

Output:

RUN 1:
Enter the elements of the matrix:
4 5 6
7 0 0
0 0 0
Matrix is a Sparse Matrix

RUN 2:
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
Matrix is not aa Sparse Matrix

Explanation:

Here, we created a 3X3 matrix matrix using the 2D array. Then we read the elements for the matrix and check given matrix is a sparse matrix or not. After that, we printed the appropriate message on the console screen.

C Two-dimensional Arrays Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.