Skip to content

Instantly share code, notes, and snippets.

@suryansh011
Created October 26, 2021 09:06
Show Gist options
  • Save suryansh011/7abc966f5049530a9944395a804f2066 to your computer and use it in GitHub Desktop.
Save suryansh011/7abc966f5049530a9944395a804f2066 to your computer and use it in GitHub Desktop.
Sparse Matrix
#include<stdio.h>
int main() {
int i, j; // Counters
int r, c;
printf("Enter size for the sparse matrix (m * n): ");
scanf("%d %d", &r, &c);
int A[r][c];
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
scanf("%d", &A[i][j]);
}
}
int size = 0;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
if(A[i][j] != 0)
size++;
int cA[3][size];
int k = 0;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
if(A[i][j] != 0) {
cA[0][k] = i;
cA[1][k] = j;
cA[2][k] = A[i][j];
k++;
}
printf("\nThe compact matrix is: \n\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < size; j++)
printf("%d ", cA[i][j]);
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment