This is a C Program to determine if a given matrix is a sparse matrix.

This C Program determines the given matrix is a sparse matrix.

Sparse matrix is a matrix with the majority of its elements equal to zero. This program accepts matrix and checks whether the given matrix is a sparse matrix.

Here is source code of the C program to determine if a given matrix is a sparse matrix. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C program to determine if a given matrix is a sparse matrix. * Sparse martix has more zero elements than nonzero elements. */ #include <stdio.h> void main () { static int array[10][10]; int i, j, m, n; int counter = 0; printf("Enter the order of the matix \n"); scanf("%d %d", &m, &n); printf("Enter the co-efficients of the matix \n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { scanf("%d", &array[i][j]); if (array[i][j] == 0) { ++counter; } } } if (counter > ((m * n) / 2)) { printf("The given matrix is sparse matrix \n"); } else printf("The given matrix is not a sparse matrix \n"); printf("There are %d number of zeros", counter); }

In this C program, we are reading the order of the matrix row and column using ‘m’ and ‘n’ variables respectively. Using for loop the coefficient elements of the matrix is assigned to the variable ‘array[i][j]’. Using if condition statement, check the coefficient element values of the matrix are equal to zero. If the condition is true then it will execute if condition statement and increment the count variable value.

The sparse matrix has more zero elements than non zero elements of the matrix. To check the given matrix is sparse matrix or not the if-else condition statement is used to check the multiplication of row and column of the matrix value of ‘m’ and ‘n’ variables respectively.

When dividing the element values by 2 its value should be less than the number of zero elements counted by the value of ‘counter’ variable. If the condition is true, then it will display the given matrix is sparse. Otherwise, it will display the given matrix is not a sparse matrix and displays the number of zeros counted in the matrix.

$ cc pgm86.c $ a.out Enter the order of the matix 3 3 Enter the co-efficients of the matix 10 20 30 5 10 15 3 6 9 The given matrix is not a sparse matrix There are 0 number of zeros $ a.out Enter the order of the matix 3 3 Enter the co-efficients of the matix 5 0 0 0 0 5 0 5 0 The given matrix is sparse matrix There are 6 number of zeros

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms