-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathAddition_of_polynomial.c
More file actions
69 lines (61 loc) · 1.51 KB
/
Addition_of_polynomial.c
File metadata and controls
69 lines (61 loc) · 1.51 KB
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
//By Aman Dekate
//Happy Learning :)
#include <stdio.h>
#include<stdlib.h>
struct Term{
int coeff;
int exp;
};
struct Poly{
int n;
struct Term *terms;
};
void create(struct Poly *p){
int i;
printf("Number of terms?");
scanf("%d",&p->n);
p->terms=(struct Term*)malloc(p->n*sizeof(struct Term));
printf("Enter terms\n");
for(i=0;i<p->n;i++)
scanf("%d%d",&p->terms[i].coeff,&p->terms[i].exp);
}
void display(struct Poly p){
int i;
for(i=0;i<p.n;i++)
printf("%dx%d+",p.terms[i].coeff,p.terms[i].exp);
printf("\n");
}
struct Poly *add(struct Poly *p1,struct Poly *p2){
int i,j,k;
struct Poly *sum;
sum=(struct Poly*)malloc(sizeof(struct Poly));
sum->terms=(struct Term *)malloc((p1->n+p2->n)*sizeof(struct Term));
i=j=k=0;
while(i<p1->n && j<p2->n){
if(p1->terms[i].exp>p2->terms[j].exp)
sum->terms[k++]=p1->terms[i++];
else if(p1->terms[i].exp < p2->terms[j].exp)
sum->terms[k++]=p2->terms[j++];
else{
sum->terms[k].exp=p1->terms[i].exp;
sum->terms[k++].coeff=p1->terms[i++].coeff+p2->terms[j++].coeff;
}
}
for(;i<p1->n;i++)sum->terms[k++]=p1->terms[i];
for(;j<p2->n;j++)sum->terms[k++]=p2->terms[j];
sum->n=k;
return sum;
}
int main(){
struct Poly p1,p2,*p3;
create(&p1);
create(&p2);
p3=add(&p1,&p2);
printf("\n");
display(p1);
printf("\n");
display(p2);
printf("\n");
display(*p3);
return 0;
}