Multiplication of Two Polynomials Using Array in c++

Multiplication of Two Polynomials Using Array in c++. The logic of multiplication of two polynomial will same
#include<iostream.h>
#include<conio.h>
#include<string.h>
#define MAX 10
class polynomial
{
public:
struct term
{
int expo;
int coef;
}t[MAX];
int n;
polynomial()
{
n=0;
t[0].coef=0;
t[0].expo=0;
}
void setpoly(int no)
{
n=no;
int i;
cout<<“enter polynomial details \n”;
for(i=0;i<n;i++)
{
cout<<“\n enter coeff. : “;
cin>>t[i].coef;
cout<<“\n enter expo : “;
cin>>t[i].expo;

}
}
void display ()
{
cout<<“\n poly is \n”;
for(int i=0;i<n;i++)
{
cout<<” “<<t[i].coef<<“X^” <<t[i].expo<<” + “;
}
}
friend void multpoly(polynomial p1,polynomial p2);
};
void multpoly(polynomial p1,polynomial p2)
{
int terms,j,i,k=0,l=0;
polynomial p3,p4;
for(i=0;i<p1.n;i++)
{
for(j=0;j<p2.n;j++)
{
p3.t[k].coef=p1.t[i].coef*p2.t[j].coef;
p3.t[k].expo=p1.t[i].expo+p2.t[j].expo;
k++;
}
}
p3.n=k;
//p3.display();
int flag;

for(i=0;i<p3.n;i++)
{
flag=0;
for(j=i+1;j<p3.n;j++)
{
if(p3.t[i].expo==p3.t[j].expo)
{
p4.t[l].coef=p3.t[i].coef+p3.t[j].coef;
p4.t[l].expo=p3.t[i].expo;
l++;
i++;
flag=1;
}

}
if(flag==0)
{
p4.t[l].coef=p3.t[i].coef;
p4.t[l].expo=p3.t[i].expo;
l++;
}
}
p4.n=l;
cout<<“\n final poly is “;
p4.display();

}
void main()
{
clrscr();
polynomial p1,p2;
int n;
cout<<“\n enter number of terms in poly “;
cin>>n;
p1.setpoly(n);
cout<<“\n enter number of terms in poly “;
cin>>n;
p2.setpoly(n);

p1.display();
p2.display();
multpoly(p1,p2);

getch();
}

1 comment

you explained me neat this code with example

Leave a Reply