Home > Backend Development > C++ > C program for sparse matrix

C program for sparse matrix

PHPz
Release: 2023-08-27 17:37:06
forward
657 people have browsed it

C program for sparse matrix

In a given matrix, when most of the elements are zero, we call it a sparse matrix. Example - 3 x3 matrix

1 1 0
0 0 2
0 0 0
Copy after login

In this matrix, most of the elements are zeros, so it is a sparse matrix.

Question

Check whether a matrix is ​​sparse.

Solution

  • #Let us assume that the zeros in the matrix are greater than (number of rows * number of columns)/2.

  • Then, this matrix is ​​a sparse matrix, otherwise it is not.

Procedure

The following is the program to check if a given matrix is ​​sparse:

Demonstration

#include<stdio.h>
#include<stdlib.h>
int main(){
   int row,col,i,j,a[10][10],count = 0;
   printf("Enter row</p><p>");
   scanf("%d",&row);
   printf("Enter Column</p><p>");
   scanf("%d",&col);
   printf("Enter Element of Matrix1</p><p>");
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         scanf("%d",&a[i][j]);
      }
   }
   printf("Elements are:</p><p>");
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         printf("%d\t",a[i][j]);
      }
      printf("</p><p>");
   }
   /*checking sparse of matrix*/
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         if(a[i][j] == 0)
            count++;
      }
   }
   if(count > ((row * col)/2))
      printf("Matrix is a sparse matrix </p><p>");
   else
      printf("Matrix is not sparse matrix</p><p>");
}
Copy after login

Output

When the above program is executed, the following results will be produced-

Run 1:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 2 0 2 0
Elements are:
1 0
2 0
2 0
Matrix is not sparse matrix
Run 2:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 0 0 0 0
Elements are:
1 0
0 0
0 0
Matrix is a sparse matrix
Copy after login

The above is the detailed content of C program for sparse matrix. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template