1//Addition of Two Polynomial
2
3#include <iostream.h>
4#include <iomanip.h>
5#include <conio.h>
6
7struct poly{
8 int coeff;
9 int pow;
10 poly *next;
11};
12
13class add2poly
14{
15 poly *poly1, *poly2, *poly3;
16 public:
17 add2poly(){poly1=poly2=poly3=NULL;}
18 void addpoly();
19 void display();
20};
21
22void add2poly :: addpoly(){
23 int i,p;
24 poly *newl=NULL,*end=NULL;
25 cout<<"Enter highest power for x\n";
26 cin>>p;
27 //Read first poly
28 cout<<"\nFirst Polynomial\n";
29 for(i=p;i>=0;i--)
30 {
31 newl=new poly;
32 newl->pow=p;
33 cout<<"Enter Co-efficient for degree"<<i<<":: ";
34 cin>>newl->coeff;
35 newl->next=NULL;
36 if(poly1==NULL)
37 poly1=newl;
38 else
39 end->next=newl;
40 end=newl;
41 }
42
43 //Read Second poly
44 cout<<"\n\nSecond Polynomial\n";
45 end=NULL;
46 for(i=p;i>=0;i--)
47 {
48 newl=new poly;
49 newl->pow=p;
50 cout<<"Enter Co-efficient for degree"<<i<<":: ";
51 cin>>newl->coeff;
52 newl->next=NULL;
53 if(poly2==NULL)
54 poly2=newl;
55 else
56 end->next=newl;
57 end=newl;
58 }
59
60 //Addition Logic
61 poly *p1=poly1,*p2=poly2;
62 end=NULL;
63 while(p1 !=NULL && p2!=NULL){
64 if(p1->pow == p2->pow){
65 newl=new poly;
66 newl->pow=p--;
67 newl->coeff=p1->coeff + p2->coeff;
68 newl->next=NULL;
69 if(poly3==NULL)
70 poly3=newl;
71 else
72 end->next=newl;
73 end=newl;
74 }
75 p1=p1->next;
76 p2=p2->next;
77 }
78}
79
80void add2poly :: display(){
81 poly *t=poly3;
82 cout<<"\n\nAnswer after addition is : ";
83 while(t!=NULL){
84 cout.setf(ios::showpos);
85 cout<<t->coeff;
86 cout.unsetf(ios::showpos);
87 cout<<"X"<<t->pow;
88 t=t->next;
89 }
90}
91
92
93void main(){
94 clrscr();
95 add2poly obj;
96 obj.addpoly();
97 obj.display();
98 getch();
99}