Custom Search

Friday 31 August 2012

Polynomial Additon


Author: Sanif S S 
Site: theeduzone.blogspot.com 
Email: sanifss@gmail.com


#include<stdio.h>
#include<conio.h>

struct poly
{
int coef;
int exp;
};
class polynomial
{ poly p[10];
int n;
public:
 void read();
 void display();
 polynomial operator+(polynomial);
 };
 void polynomial::read()
 {
 poly temp;
 cout<<"Enter number of terms\n";
 cin>>n;

 for(int i=0;i{
 cout<<"Enter coefficient"<<" "< cin>>p[i].coef>>p[i].exp;
 }
 for( i=n-1;i>0;i--)
{
 for(int j=0;j  {
   if(p[j].exp

   {
    temp=p[j];
   p[j]=p[j+1];
   p[j+1]=temp;
 }
 }
 }
 }
 void polynomial::display()
 {
 for(int i=0;i {
 cout<

 if(i!=n-1)
 cout<<"+";
 }
 cout<<"\n";
 }
polynomial polynomial::operator +(polynomial p2)
{
 polynomial p3;
int i=0;
int j=0;
int k=0;
while(i{
if(p[i].exp>p2.p[j].exp)
{
p3.p[k]=p[i];
i++;
}
else if(p[i].exp
{
p3.p[k]=p2.p[j];
j++;
}
else
{
p3.p[k].coef=p[i].coef+p2.p[j].coef;
p3.p[k].exp=p[i].exp;
i++;
j++;
}
k++;
}
while(i
{
p3.p[k]=p[i];
i++;
k++;
}
while(j
{
p3.p[k]=p2.p[j];
j++;
k++;
}
p3.n=k;

return p3;
}
 void main()
 {
 polynomial p1,p2,p3;
 clrscr();
 cout<<"enter the first polynomial\n";
 p1.read();
 cout<<"\nenter the second polynomial\n";
 p2.read();
 cout<<"\nfirst polynomial is\n";
 p1.display();
 cout<<"\nsecond polynomial is\n";
 p2.display();
 cout<<"\nResultant polynomial is\n";
 p3=p1+p2;
 p3.display();
 getch();
 }

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...