Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to check if a given matrix is a sparse matrix (contains a large number of zeros) in C

1 Answer

0 votes
// A Sparse Matrix is a matrix with a number of  0's greater than the number of non-zero elements

#include <stdio.h> 

int main()
{   
    int matrix[3][3] = {{2, 0, 5},
                        {0, 4, 0},
                        {0, 8, 0}};
  
    size_t rows = sizeof matrix/sizeof matrix[0];
    size_t cols = (sizeof matrix/sizeof matrix[0][0])/rows;
 
    int counter = 0;
    for (int i = 0; i < rows; i++) {
		for (int j = 0; j < cols; j++) {
			if (matrix[i][j] == 0) {
                counter++;
            }
		}
	}

 
	if (counter > ((rows * cols) / 2)) {
		printf("Sparse matrix");
	}
	else {
		printf("NOT sparse matrix");
	}
     
    return 0;
}
 
 
 
   
/*
run:
 
Sparse matrix
 
*/

 



answered Jan 18, 2021 by avibootz
edited Feb 26, 2023 by avibootz
...