Operations On Polynomials
/***************************************************
-> This C++ Program is to implement the following operations
on two polynomials
1.Addition
2.Substraction
-> Linked list data structure is used to represent a polynomial
-> Eg. of a polynomial is : 3*x^2 + 2*x^1 + 1
-> This program works well in the microsoft vc++ 6.0 environment
***************************************************/
#include
class polynomial
{
private:
int a,n;
polynomial *next;
public:
polynomial* read_polynomial(polynomial *);
void print_polynomial(polynomial *);
void add_polynomials(polynomial *,polynomial *);
void sub_polynomials(polynomial *,polynomial *);
void function();
};
polynomial* polynomial::read_polynomial(polynomial *p)
{
int a,n;
polynomial *NEW;
polynomial *tail;
cout<<”Now enter coefficient followed by exponent for the first term\n”;
cin>>a>>n;
while(n!=-1)
{
NEW=new polynomial;
NEW->a=a;
NEW->n=n;
NEW->next=NULL;
if(p==NULL)
p=NEW;
else
tail->next=NEW;
tail=NEW;
cout<<”Enter coefficient followed by exponent for the next term\n”;
cin>>a>>n;
}
return p;
}
void polynomial::print_polynomial(polynomial *p)
{
while(p!=NULL)
{
cout<
if(p->n!=0)
{
cout<<”*x^”;
cout<
}
if(p->next!=NULL)
cout<<”+ “;
p=p->next;
}
}
void polynomial::add_polynomials(polynomial*p,polynomial*q)
{
while(p!=NULL && q!=NULL)
{
if(p->n > q->n)
{
cout<
p=p->next;
}
else if(p->n <>n)
{
cout<
q=q->next;
}
else
{
cout<
p=p->next;
q=q->next;
}
}
while(p!=NULL)
{
cout<
p=p->next;
}
while(q!=NULL)
{
cout<
q=q->next;
}
cout<<0<
void polynomial::sub_polynomials(polynomial*p,polynomial*q)
{
while(p!=NULL && q!=NULL)
{
if(p->n > q->n)
{
cout<
p=p->next;
}
else if(p->n <>n)
{
cout<<-q->a<<”*x^”<
q=q->next;
}
else
{
if(p->a-q->a != 0)
cout<
p=p->next;
q=q->next;
}
}
while(p!=NULL)
{
cout<
p=p->next;
}
while(q!=NULL)
{
cout<<-q->a<<”*x^”<
q=q->next;
}
cout<<”0″<
void polynomial::function()
{
cout<<”********Instructions for Entering a polynomial********\n”;
cout<<”Enter coefficient followed by exponent for each term\n”;
cout<<”Enter exponents in the decreasing order\n”;
cout<<”Enter Exponent -1 to stop\n\n\n”;
cout<<”Enter the first polynomial P::\n\n”;
cout<<”Enter the second polynomial Q::\n\n”;
cout<<”The sum of the given two polynomials is P+Q ::\n”;
} int main()
polynomial *p=NULL;
p=read_polynomial(p);
cout<<”\nThe entered polynomial is ::\n”;
print_polynomial(p);
cout<
polynomial *q=NULL;
q=read_polynomial(q);
cout<<”\nThe entered polynomial is ::\n”;
print_polynomial(q);
cout<
add_polynomials(p,q);
cout<<”\nThe difference of the given two polynomials is P-Q ::\n”;
sub_polynomials(p,q);
{
polynomial obj;
obj.function();
return 0;
}
0 comments:
Post a Comment