-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolynomial_addition.c
99 lines (97 loc) · 2.04 KB
/
polynomial_addition.c
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
93
94
95
96
97
98
99
//polynomial representation
#include<stdio.h>
#include<stdlib.h>
struct node{
float coeff;
int expo;
struct node *next;
};
typedef struct node Node;
Node *insert_a_term(Node *head,float co,int ex){
Node *NN;
NN=(Node *)malloc(sizeof(Node));
NN->coeff=co;
NN->expo=ex;
NN->next=NULL;
if(head==NULL || NN->expo > head->expo){
NN->next=head;
head=NN;
}
else{
Node *temp=head;
while(temp->next!=NULL &&temp->next->expo >ex){
temp=temp->next;
}
NN->next=temp->next;
temp->next=NN;
}
return head;
}
Node *create_polynomial(){
Node *head=NULL;
int n,i;
printf("enter the no of terms:\n");
scanf("%d",&n);
for(i=1;i<=n;i++){
float co;
int ex;
printf("enter the coeff of term %d:\n",i);
scanf("%f",&co);
printf("enter expo of the term %d:\n",i);
scanf("%d",&ex);
head=insert_a_term(head,co,ex);
}
return head;
}
void display_polynomial(Node *head){
Node *temp=head;
while(temp){
printf("%0.1fx^%d",temp->coeff,temp->expo);
if(temp->next!=NULL){
printf(" + ");
}
else{
printf("\n");
}
temp=temp->next;
}
}
Node *poly_addition(Node *poly1,Node *poly2){
Node *t1,*t2;
t1=poly1;
t2=poly2;
Node *head=NULL;
while(t1!=NULL &&t2!=NULL){
if(t1->expo==t2->expo){
head=insert_a_term(head,t1->coeff+t2->coeff,t1->expo);
t1=t1->next;
t2=t2->next;
}
else if (t1->expo>t2->expo){
head=insert_a_term(head,t1->coeff,t1->expo);
t1=t1->next;
}
else{
head=insert_a_term(head,t2->coeff,t2->expo);
t2=t2->next;
}
}
while(t1!=NULL){
head=insert_a_term(head,t1->coeff,t1->expo);
t1=t1->next;
}
while(t2!=NULL){
head=insert_a_term(head,t2->coeff,t2->expo);
t2=t2->next;
}return head;
}
int main(){
printf("Polynomial 1:\n");
Node *poly1=create_polynomial();//creating polynomial
printf("Polynomial 2:\n");
Node *poly2=create_polynomial();
Node *sum=poly_addition(poly1,poly2);
display_polynomial(poly1);
display_polynomial(poly2);
display_polynomial(sum);
}