ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.