forked from gunanksood/C-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSparseMatrix1.c
More file actions
executable file
·54 lines (50 loc) · 1.21 KB
/
SparseMatrix1.c
File metadata and controls
executable file
·54 lines (50 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<stdio.h>
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
int i,j;
for ( i = 0; i < 4; i++)
{
for ( j = 0; j < 5; j++)
{
if (sparseMatrix[i][j] != 0)
{
size++;
}
}
}
// number of columns in compactMatrix (size) must be
// equal to number of non - zero elements in
// sparseMatrix
int compactMatrix[3][size+1];
// Making of new matrix
int k = 0;
compactMatrix[0][k] = 4;
compactMatrix[1][k] = 5;
compactMatrix[2][k] = size;
k++;
for ( i = 0; i < 4; i++)
for ( j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
for ( i=0; i<3; i++)
{
for ( j=0; j<size+1; j++)
printf("%d ", compactMatrix[i][j]);
printf("\n");
}
return 0;
}