C++ program to subtract two polynomials.
C++ program to subtract two polynomials using array
#include<iostream>
using namespace std;
int subpoly(int (&a)[10][2],int (&b)[10][2],int (&c)[10][2],int n1,int n2)
{
int i=0,j=0,k=0;
while(1)
{
if(a[i][1]<b[j][1])
{
c[k][0]=-b[j][0];
c[k][1]=b[j][1];
k++,j++;
}
else if(a[i][1]>b[j][1])
{
c[k][0]=a[i][0];
c[k][1]=a[i][1];
k++,i++;
}
else
{
c[k][0]=a[i][0]-b[j][0];
c[k][1]=a[i][1];
i++,j++,k++;
if(c[k][0])
k--;
}
if(j==n2)
{
while(i<n1)
{
c[k][0]=a[i][0];
c[k][1]=a[i][1];
k++,i++;
}
}
if(i==n1)
{
while(j<n2)
{
c[k][0]=-b[j][0];
c[k][1]=b[j][1];
k++,j++;
}
}
if(i==n1)
break;
}
return k;
}
void print(int (&d)[10][2],int n)
{
for(int i=0;i<n-1;i++)
cout<<d[i][0]<<"x^"<<d[i][1]<<" + ";
cout<<d[n-1][0]<<"x^"<<d[n-1][1]<<endl<<endl;
}
void getpoly(int (&d)[10][2],int &n)
{
cout<<"How many terms in polynomial ";
cin>>n;
cout<<"Enter coefficient and exponent in decreasing order"<<endl;
for(int i=0;i<n;i++)
cin>>d[i][0]>>d[i][1];
}
int main()
{
int a[10][2],b[10][2],c[10][2],n1,n2,n3;
getpoly(a,n1);
print(a,n1);
getpoly(b,n2);
print(b,n2);
n3=subpoly(a,b,c,n1,n2);
cout<<"Subtraction of two polynomials"<<endl;
print(c,n3);
return 0;
}
OUTPUT
using namespace std;
int subpoly(int (&a)[10][2],int (&b)[10][2],int (&c)[10][2],int n1,int n2)
{
int i=0,j=0,k=0;
while(1)
{
if(a[i][1]<b[j][1])
{
c[k][0]=-b[j][0];
c[k][1]=b[j][1];
k++,j++;
}
else if(a[i][1]>b[j][1])
{
c[k][0]=a[i][0];
c[k][1]=a[i][1];
k++,i++;
}
else
{
c[k][0]=a[i][0]-b[j][0];
c[k][1]=a[i][1];
i++,j++,k++;
if(c[k][0])
k--;
}
if(j==n2)
{
while(i<n1)
{
c[k][0]=a[i][0];
c[k][1]=a[i][1];
k++,i++;
}
}
if(i==n1)
{
while(j<n2)
{
c[k][0]=-b[j][0];
c[k][1]=b[j][1];
k++,j++;
}
}
if(i==n1)
break;
}
return k;
}
void print(int (&d)[10][2],int n)
{
for(int i=0;i<n-1;i++)
cout<<d[i][0]<<"x^"<<d[i][1]<<" + ";
cout<<d[n-1][0]<<"x^"<<d[n-1][1]<<endl<<endl;
}
void getpoly(int (&d)[10][2],int &n)
{
cout<<"How many terms in polynomial ";
cin>>n;
cout<<"Enter coefficient and exponent in decreasing order"<<endl;
for(int i=0;i<n;i++)
cin>>d[i][0]>>d[i][1];
}
int main()
{
int a[10][2],b[10][2],c[10][2],n1,n2,n3;
getpoly(a,n1);
print(a,n1);
getpoly(b,n2);
print(b,n2);
n3=subpoly(a,b,c,n1,n2);
cout<<"Subtraction of two polynomials"<<endl;
print(c,n3);
return 0;
}
OUTPUT
No comments:
Post a Comment