Tuesday, 29 October 2013

Sparse Matrix in C

If a matrix contains lots of ZEROS , then to save time & space,we use a special type of matrix ,known as SPARSE MATRIX.....

It stores only the NON-ZERO Elements only....
It can be created by two ways
1)Using array
2)Using Linklist

Simple e.g-


Let's write a c programe to get the sparse matrix of a given matix [In array]

 #include<stdio.h>  
 #include<stdlib.h>  
 int main()  
 {  
   int a[20][20],i,j,r,c,templ[40],tempv[40],n=0,k=0,s[40][3];  
   printf("Enter no. of rows.. ");  
   scanf("%d",&r);   
   printf("Enter no. of columns.. ");  
   scanf("%d",&c);  
   for(i=0;i<r;i++)  
   { for(j=0;j<c;j++)  
      scanf("%d",&a[i][j]);  
   }  
   for(i=0;i<r;i++)  
   { for(j=0;j<c;j++)  
      printf(" %d",a[i][j]);  
    printf("\n");  
   }  
   for(i=0;i<r;i++)  
   { for(j=0;j<c;j++)  
             if(a[i][j]!=0)  
           {  k++;  s[k][0]=i;  s[k][1]=j; s[k][2]=a[i][j];}       
   }                   
   s[0][0]=r; s[0][1]=c; s[0][2]=k;  
   for(i=0;i<=k;i++)  
   {for(j=0;j<3;j++)  
      printf(" %d ",s[i][j]);  
    printf("\n");  
   }  
   system("pause");  
   return 0;  
 }  


OUTPUT:

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets