- First, specify the order of the matrix. Then, you will be prompted to enter the elements in the matrix. Let's assume that you specified the order of the matrix as 4 x 4. After entering the elements in the matrix, it might appear like this:
Figure 1.21
- Once the elements of the matrix are entered, count the number of zeros in it. A counter for this purpose is initialized to 0. Using nested loops, each of the matrix elements is scanned and, upon finding any zero elements, the value of the counter is incremented by 1.
- Thereafter, the following formula is used for establishing whether the matrix is sparse.
If counter > [(the number of rows x the number of columns)/2] = Sparse Matrix
- Depending on the result of the preceding formula, one of the following messages will be displayed on the screen as follows:
The given matrix is a sparse matrix
or
The given matrix is not a sparse matrix
The sparsematrix.c program for establishing whether the matrix is sparse is as follows:
#include <stdio.h>
#define max 100
/*A sparse matrix has more zero elements than nonzero elements */
void main ()
{
static int arr[max][max];
int i,j,r,c;
int ctr=0;
printf("How many rows and columns are in this matrix? ");
scanf("%d %d", &r, &c);
printf("Enter the elements in the matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&arr[i][j]);
if (arr[i][j]==0)
++ctr;
}
}
if (ctr>((r*c)/2))
printf ("The given matrix is a sparse matrix. \n");
else
printf ("The given matrix is not a sparse matrix.\n");
printf ("There are %d number of zeros in the matrix.\n",ctr);
}
Now, let's go behind the scenes to understand the code better.