Aim:
Write a C++ program for the addition of two polynomial expressions
Program:
#include<iostream.h> #include<conio.h> class poly { struct { int coef; int expo; } term[20]; int degree; public: void input() { int i; cout<<"Enter number of terms"; cin>>degree; cout<<"Enter coefficients and exponents for " << degree <<" terms"<<endl; for(i=0;i<degree;i++) cin>>term[i].coef>>term[i].expo; } void add(poly A, poly B) { int i,j,k,l; degree=A.degree+B.degree; i=0;j=0;k=0; while(i<A.degree && j<B.degree) { if( A.term[i].expo<B.term[j].expo) { term[k].coef=B.term[j].coef; term[k].expo=B.term[j].expo; j++; k++; } if( A.term[i].expo>B.term[j].expo) { term[k].coef=A.term[i].coef; term[k].expo=A.term[i].expo; i++; k++; } if( A.term[i].expo==B.term[j].expo) { term[k].coef=A.term[i].coef+B.term[j].coef; term[k].expo=A.term[i].expo; i++; j++; k++; } } if(i<A.degree) { for(l=i; l<A.degree; l++) { term[k].coef=A.term[l].coef; term[k].expo=A.term[l].expo; k++; } } if(j<B.degree) { for(l=j; l<B.degree; l++) { term[k].coef=B.term[l].coef; term[k].expo=B.term[l].expo; k++; } } degree=k; } void display() { int i; cout<<"polynomial is"<<endl; for(i=0;i<degree;i++) cout<<term[i].coef<<"x"<<term[i].expo<<" "; } }; main() { poly A,B,C; cout<<"Enter Polynomial A:"<<endl; A.input(); cout<<"Enter Polynomial B:"<<endl; B.input(); C.add(A,B); C.display(); getch(); }
Output:
Enter Polynomial A: Enter number of terms 3 Enter coefficients and exponents for 3 terms 3 2 4 1 6 0 Enter Polynomial B: Enter number of terms 3 Enter coefficients and exponents for 3 terms 5 2 5 1 8 0 Polynomial is 8x2 9x1 14x0
Result:
Thus, the addition of two polynomial expressions was successfully executed.