C PROGRAMMING PROGRAM • MATRICES
Check Whether a Matrix Is Sparse
Learn how to check whether a matrix is sparse using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
3 3 1 0 0 0 0 2 0 0 0
Sample output
Sparse matrix
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int rows, columns, matrix[10][10], zeroCount = 0;
scanf("%d %d", &rows, &columns);
if (rows < 1 || rows > 10 || columns < 1 || columns > 10) return 1;
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++) {
scanf("%d", &matrix[row][column]);
if (matrix[row][column] == 0) zeroCount++;
}
printf(zeroCount > rows * columns / 2 ? "Sparse matrix\n" : "Not a sparse matrix\n");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sparse matrix
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Count zeros and classify the matrix as sparse when more than half of its entries are zero.
- Display the computed result.
Count zeros and classify the matrix as sparse when more than half of its entries are zero.
EFFICIENCY
Time and space complexity
Time complexity
O(rows × columns)
Auxiliary space
O(rows × columns)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
