Welcome To Cbitcse 2k12



[+] Post Title :

Data Structures Implementation Polynomial Addition using array in C++


[+] Date : Sunday 20 October 2013
[+] Author : Prudhvi raj
[+] Type :
#include<iostrea.h>
#include<conio.h>
class polynomial
{
int coeff[10],deg[10],size;
public:
void getpoly();
polynomial operator+(polynomial);
void convert(void);
void adjust();
void display(void);
};
void polynomial::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];
}
}
void polynomial::convert()
{
int temp,temp2;
for(int i=0;i<size;i++)
{
for(int j=i+1j<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;
}}}
}
polynomial polynomial::operator+(polynomial p)
{
polynomial 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);
}
void polynomial::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
{
dege[i]=deg[i];
coeff[i]=coeff[i];
}}
}
display();
convert();
}
void polynomial::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<<"+";
}}
}
void main()
{ polynomial a,b,c;
clrscr();
cout<<"\n\tINPUT";
cout<<"\n\t*****";
a.getpoly();
b.getpoly();
a.convert();
b.convert();
c=a+b;
cout<<endl;
cout<<"\n\tOUTPUT";
cout<<"\n\t******";
cout<<"\n\tFirst polynomial:";
a.display();
cout<<"\n\tSecond polynomial:";
b.display();
cout<<"\n\tThe added values is:";
c.display();
cout<<"\n\n\n";
getch();
}
 


Input:
Enter the size:2

Enter the co-efficent:4
Enter the degree:2
Enter the co-efficent:5
Enter the degree:1
Enter the size:2
Enter the co-efficent:7
Enter the degree:2
Enter the co-efficent:6
Enter the degree:1
 
users online