Because we don't want to fix the size of the matrix, we will define a macro called max of value 100. A matrix, or a two-dimensional array called arr, is defined of the order max x max. You will be prompted to enter the order of the matrix, for which you can again enter any value up to 100.
Let's assume that you’ve specified the order of the matrix as 4 x 4. You will be prompted to enter elements in the matrix. The values entered in the matrix will be in row-major order. After entering the elements, the matrix arr should look like Figure 1.22, as follows:
A counter called ctr is created and is initialized to 0. Using nested loops, each element of matrix arr is checked and the value of ctr is incremented if any element is found to be 0. Thereafter, using the if else statement, we will check whether the count of zero values is more than non-zero values. If the count of zero values is more than non-zero values, then the message will be displayed on the screen as follows:
The given matrix is a sparse matrix
However, failing that, the message will be displayed on the screen as follows:
The given matrix is not a sparse matrix
Let's use GCC to compile the sparsematrix.c program as follows:
D:\CBook>gcc sparsematrix.c -o sparsematrix
Let's run the generated executable file, sparsematrix.exe, to see the output of the program:
D:\CBook>./sparsematrix
How many rows and columns are in this matrix? 4 4
Enter the elements in the matrix :
0 1 0 0
5 0 0 9
0 0 3 0
2 0 4 0
The given matrix is a sparse matrix.
There are 10 zeros in the matrix.
Okay. Let's run the program again to see the output when the count of non-zero values is higher:
D:\CBook>./sparsematrix
How many rows and columns are in this matrix? 4 4
Enter the elements in the matrix:
1 0 3 4
0 0 2 9
8 6 5 1
0 7 0 4
The given matrix is not a sparse matrix.
There are 5 zeros in the matrix.
Voilà! We've successfully identified a sparse and a non-sparse matrix.