Hi GuyZ,
This is a simple programming problem asked during your BCA/MCA/B.Tech Data Structures and Algorithms paper.
This is a simple programming problem asked during your BCA/MCA/B.Tech Data Structures and Algorithms paper.
Source Code
#include <iostream> #include <stdlib.h> using namespace std; /* Coded By Ajith Kp [ ajithkp560 ] (c) _TERMINAL_CODERS http://www.terminalcoders.blogspot.com (c) */ struct tripp { int r, c, v; }; class sparse { int i, j, k, cc, cr, crb, sum, f[1024], pc[1024]; public: tripp a[1024], b[1024]; void read() { cout<<"Enter r, c & v: "; cin>>a[0].r>>a[0].c>>a[0].v; for(i=1;i<=a[0].v;i++) { cin>>a[i].r>>a[i].c>>a[i].v; } } void show() { k = 1; for(i=0;i<a[0].r;i++) { for(j=0;j<a[0].c;j++) { if(a[k].r==i && a[k].c==j) { cout<<a[k++].v<<"\t"; } else cout<<"0\t"; } cout<<"\n"; } } void sort() { b[0] = a[0]; for(i=0;i<a[0].c;i++)f[i] = 0; for(i=1;i<=a[0].v;i++)f[a[i].c]++; pc[0] = 1; for(i=1;i<a[0].c;i++)pc[i]=f[i-1]+pc[i-1]; for(i=1;i<=a[0].v;i++) { b[pc[a[i].c]] = a[i]; pc[a[i].c]++; } } sparse operator*(sparse sp) { if(a[0].c!=sp.b[0].r) { cout<<"Cannot perform operation\n"; exit(0); } sparse s; k=1; i=1; s.a[0].r = a[0].r; s.a[0].c = sp.b[0].c; while(i<=a[0].v) { crb=i; j=1; while(j<=sp.b[0].v) { cr=a[i].r; cc=sp.b[j].c; sum=0; while(i<=a[0].v && j<=sp.b[0].v && cr==a[i].r && cc==sp.b[j].c) { if(a[i].c==sp.b[j].r) { sum+=a[i].v*sp.b[j].v; i++;j++; } else if(a[i].c<sp.b[j].r) i++; else j++; } if(sum) { s.a[k].r=cr; s.a[k].c=cc; s.a[k].v=sum; k++; } i=crb; while(cc==sp.b[j].c) j++; } while(cr==a[i].r) i++; } s.a[0].v = k; return s; } }; int main() { sparse s1, s2, s3; s1.read(); s2.read(); cout<<"\nFirst matrix: \n"; s1.show(); cout<<"\nSecond Matrix: \n"; s2.show(); s2.sort(); s3=s1*s2; cout<<"\n\nResult of multiplication:\n"; s3.show(); }