/* C++ program for Polynomial using Template */
#include<iostream>
using namespace std;
template <class T>
class polynomial
{
T coeff[10];
int deg[10],size;
void display();
public:
void getpoly();
polynomial operator+(polynomial);
void swap();
void adjust();
};
template <class T>
void polynomial<T>::getpoly()
{
cout<<"\n\tEnter the size:";
cin>>size;
for(int i=0;i<size;i++)
{
cout<<"\n\tEnter the co-efficent:";
cin>>coeff[i];
cout<<"\n\tEnter the degree:";
cin>>deg[i];
}
}
template <class T>
void polynomial<T>::swap()
{
T temp,temp2;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(deg[j]>deg[i])
{
temp=deg[j];
temp2=coeff[j];
deg[j]=deg[i];
coeff[j]=coeff[i];
deg[i]=temp;
coeff[i]=temp2;
}
}
}
}
template <class T>
polynomial<T> polynomial<T>::operator+(polynomial<T> p)
{
polynomial<T> temp;
int i=0,j=0,k=0;
while((i<size)&&(j<p.size))
{
if(deg[i]==p.deg[i])
{
temp.coeff[k]=coeff[i]+p.coeff[j];
temp.deg[k]=deg[i];
i++;j++;
}
else
if(deg[i]<p.deg[j])
{
temp.coeff[k]=p.coeff[j];
temp.deg[k]=p.deg[j];
j++;
}
else
{
temp.coeff[k]=coeff[i];
temp.deg[k]=deg[i];
i++;
}
k++;
}
while(i!=size)
{
temp.coeff[k]=coeff[i];
temp.deg[k]=deg[i];
i++;
k++;
}
while(j!=p.size)
{
temp.coeff[k]=p.coeff[j];
temp.deg[k]=p.deg[j];
j++;
k++;
}
temp.size=k;
return(temp);
}
template <class T>
void polynomial<T>::adjust()
{
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(deg[j]==deg[i])
{
deg[i]=deg[i];
coeff[i]=coeff[i]+coeff[j];
coeff[j]=0;
deg[j]=0;
}
else
{
deg[i]=deg[i];
coeff[i]=coeff[i];
}
}
}
display();
swap();
}
template <class T>
void polynomial<T>::display()
{
for(int i=0;i<size;i++)
{
if(coeff[i]!=0)
{
cout<<coeff[i]<<"X^"<<deg[i];
if((coeff[i]>=0)&&(i<size-1))
cout<<"+";
}
}
}
int main()
{
polynomial<int> a,b,c;
cout<<"\n\tINPUT for First Polynomial";
cout<<"\n\t--------------------------";
a.getpoly();
cout<<"\n\tINPUT for Second Polynomial";
cout<<"\n\t---------------------------";
b.getpoly();
a.swap();
b.swap();
c=a+b;
cout<<endl;
cout<<"\n\tFirst polynomial";
a.adjust();
cout<<"\n\tSecond polynomial:";
b.adjust();
cout<<"\n\tThe added values is:";
c.adjust();
cout<<"\n\n\n";
return 0;
}
No comments:
Post a Comment