C Online Compiler
Example: Check Sparse Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Check Sparse Matrix #include <stdio.h> // Function to check if a matrix is sparse void checkSparseMatrix(int rows, int cols, int matrix[rows][cols]) { int zeroCount = 0; int totalElements = rows * cols; // Step 1: Iterate through the matrix to count zero elements for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == 0) { zeroCount++; } } } // Step 2: Compare zero count with the threshold // A matrix is considered sparse if the number of zero elements // is greater than half of the total elements. if (zeroCount > (totalElements / 2)) { printf("The given matrix is a Sparse Matrix.\n"); } else { printf("The given matrix is NOT a Sparse Matrix.\n"); } // Optional: Print details for clarity printf("Total elements: %d\n", totalElements); printf("Number of zero elements: %d\n", zeroCount); printf("Number of non-zero elements: %d\n", totalElements - zeroCount); } int main() { // Example 1: A Sparse Matrix int rows1 = 3; int cols1 = 3; int matrix1[3][3] = { {1, 0, 0}, {0, 2, 0}, {0, 0, 3} }; printf("--- Matrix 1 ---\n"); printf("Matrix:\n"); for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols1; j++) { printf("%d ", matrix1[i][j]); } printf("\n"); } checkSparseMatrix(rows1, cols1, matrix1); printf("\n--- Matrix 2 ---\n"); // Example 2: A Non-Sparse Matrix int rows2 = 3; int cols2 = 3; int matrix2[3][3] = { {1, 2, 3}, {4, 5, 0}, {0, 0, 0} }; printf("Matrix:\n"); for (int i = 0; i < rows2; i++) { for (int j = 0; j < cols2; j++) { printf("%d ", matrix2[i][j]); } printf("\n"); } checkSparseMatrix(rows2, cols2, matrix2); return 0; }
Output
Clear
ADVERTISEMENTS