Skip to content

Commit db4ea3b

Browse files
Added Sparse Matrix in C
1 parent 44855cf commit db4ea3b

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Matrix/sparseMatrix.c

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int nonZero;
5+
6+
void sparseMatrix(int arr[100][100],int rows,int columns){
7+
8+
int crr[rows][nonZero],p=0,q=0;
9+
10+
for(int i=0;i<rows;i++){
11+
for(int j=0;j<columns;j++){
12+
13+
if (arr[i][j]>0){
14+
crr[p][q]=i;
15+
crr[p+1][q]=j;
16+
crr[p+2][q]=arr[i][j];
17+
q++;
18+
19+
}
20+
}
21+
}
22+
23+
for(int f=0; f<rows;f++){
24+
for(int g=0;g<nonZero;g++){
25+
printf("%d ", crr[f][g]);
26+
}
27+
printf("\n");
28+
}
29+
30+
}
31+
32+
int main()
33+
{
34+
int rows,columns,arr[100][100],flag=0;
35+
printf("Enter rows of matrix: ");
36+
scanf("%d",&rows);
37+
printf("\nEnter columns of matrix: ");
38+
scanf("%d",&columns);
39+
printf("\nEnter elements of matrix:\n");
40+
for(int i=0;i<rows;i++){
41+
for(int j=0;j<columns;j++){
42+
scanf("%d",&arr[i][j]);
43+
if(arr[i][j]==0){
44+
flag++;
45+
}
46+
}
47+
}
48+
49+
nonZero = (rows*columns)- flag;
50+
if (flag>=nonZero){
51+
printf("\nSparse Matrix:\n");
52+
sparseMatrix(arr,rows,columns);
53+
}else{
54+
printf("\nNot a sparse matrix");
55+
}
56+
57+
58+
59+
60+
61+
62+
63+
return 0;
64+
}

0 commit comments

Comments
 (0)