-
Notifications
You must be signed in to change notification settings - Fork 1
/
Poly2.cpp
92 lines (84 loc) · 2.05 KB
/
Poly2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
using namespace std;
struct poly
{
int coeff;
int pow_val;
poly* next;
};
class add
{
poly *poly1, *poly2, *poly3;
public:
add() { poly1 = poly2 = poly3 = NULL; }
void addpoly();
void display();
};
void add::addpoly()
{
int i, p,q,c;
poly *newl = NULL, *end = NULL;
cout << "Enter highest power for x\n in 1st polynomial";
cin >> p;
cout << "Enter highest power for x\n in 2nd polynomial";
cin>>q;
c=max(p,q);
cout << "\nFirst Polynomial\n"; for (i = p; i >= 0; i--) {
newl = new poly;
newl->pow_val = p;
cout << "Enter Co-efficient for degree" << i << ":: "; cin >> newl->coeff;
newl->next = NULL;
if (poly1 == NULL)
poly1 = newl;
else
end->next = newl;
end = newl;
}
cout << "\n\nSecond Polynomial\n"; end = NULL; for (i = q; i >= 0; i--) {
newl = new poly;
newl->pow_val = q;
cout << "Enter Co-efficient for degree" << i << ":: "; cin >> newl->coeff;
newl->next = NULL;
if (poly2 == NULL)
poly2 = newl;
else
end->next = newl;
end = newl;
}
poly *p1 = poly1, *q1 = poly2;
end = NULL;
while (p1 != NULL && q1 != NULL)
{
if (p1->pow_val == q1->pow_val) {
newl = new poly;
newl->pow_val=c--;
newl->coeff = p1->coeff + q1->coeff;
newl->next = NULL;
if (poly3 == NULL)
poly3 = newl;
else
end->next = newl;
end = newl;
}
p1 = p1->next;
q1 = q1->next;
}
}
void add::display()
{
poly* t = poly3;
cout << "\n\nAnswer after addition is : ";
while (t != NULL) {
cout.setf(ios::showpos);
cout << t->coeff;
cout.unsetf(ios::showpos);
cout << "X" << t->pow_val;
t = t->next;
}
}
int main()
{
add obj;
obj.addpoly();
obj.display();
}