My photo
Bangalore, Karnataka, India
Extending one hand to help someone has more value rather than joining two hands for prayer

Archives

program of sparse matrix

Tuesday, September 1, 2009

#include<iostream.h>
#include<conio.h>
void main()
{  clrscr();
   int n,m;
   cout<<"enter the size of array: ";
   cin>>n>>m;
   int **p=new *[n];

//   for(int l=0;l<n;l++)
//   { cout<<(p+l)<<endl; }    array of pointer allocate contigue memory

   for(int i=0;i<n;i++)
   *(p+i)=new int[m];
   cout<<"enter the elements: ";
   for(i=0;i<n;i++)
   for(int j=0;j<m;j++)
   cin>>*(*(p+i)+j);
   cout<<"sparse matrix is: "<<endl;
   for(i=0;i<n;i++)
   {  for(j=0;j<m;j++)
      cout<<*(*(p+i)+j)<<" ";
      cout<<endl;              }
   int a,b,k;
   a=b=0;
   k=1;
   for(i=0;i<n;i++)
   {   for(j=0;j<m;j++)
       {   if(*(*(p+i)+j)!=0)
         {    k++; }
                 }
                   }
   int **p1=new *[k];
   for(i=0;i<k;i++)
   *(p1+i)=new int[3];
   *(*(p1+a)+b)=n;
   b++;
   *(*(p1+a)+b)=m;
   b++;
   *(*(p1+a)+b)=k-1;
   a++;
   for(i=0;i<n;i++)
   {   for(j=0;j<m;j++)
       {    if(*(*(p+i)+j)!=0)
           {   b=0;
           *(*(p1+a)+b)=i+1;
           b++;
           *(*(p1+a)+b)=j+1;
           b++;
           *(*(p1+a)+b)=*(*(p+i)+j);
           a++;                        }
                              }
                                   }
    cout<<"triplet matrix is: "<<endl;
    for(i=0;i<a;i++)
    {   for(j=0;j<3;j++)
    cout<<*(*(p1+i)+j)<<" ";
    cout<<endl;                }
    getch();
  }

0 comments: