1// Aim: Program to perform Polynomial operations (Addition, Multiplication).
2#include<stdio.h>
3struct poly{
4 int coeff;
5 int expo;
6}p1[10],p2[10],p3[10];
7
8int read(struct poly p[]);
9int add(struct poly [],struct poly [],int,int,struct poly []);
10void display(struct poly [],int);
11
12void main(){
13 int t1,t2,t3;
14 t1=read(p1);
15 t2=read(p2);
16 t3=add(p1,p2,t1,t2,p3);
17 printf("Polynomial 1\n");
18 display(p1,t1);
19 printf("Polynomial 2\n");
20 display(p2,t2);
21 printf("Resulting polynomial\n");
22 display(p3,t3);
23}
24
25int read(struct poly p1[]){
26 int t1,i;
27 printf("Enter the number of terms in the polynomial: ");
28 scanf("%d",&t1);
29 printf("Enter the polynomial terms with coeff and expo in descending order\n");
30 for(i=0;i<t1;i++){
31 scanf("%d %d",&p1[i].coeff,&p1[i].expo);
32 }
33 return t1;
34}
35
36int add(struct poly p1[],struct poly p2[],int t1,int t2,struct poly p3[]){
37 int i=0,j=0,k=0;
38 while(i<t1 && j<t2){
39 if(p1[i].expo==p2[j].expo){
40 p3[k].coeff=p1[i].coeff+p2[j].coeff;
41 p3[k].expo=p1[i].expo;
42 i++;
43 j++;
44 k++;
45 }
46 else if(p1[i].expo>p2[j].expo){
47 p3[k].coeff=p1[i].coeff;
48 p3[k].expo=p1[i].expo;
49 i++;
50 k++;
51 }
52 else{
53 p3[k].coeff=p2[j].coeff;
54 p3[k].expo=p2[j].expo;
55 j++;
56 k++;
57 }
58 }
59 while(i<t1){
60 p3[k].coeff=p1[i].coeff;
61 p3[k].expo=p1[i].expo;
62 i++;
63 k++;
64 }
65 while(j<t2){
66 p3[k].coeff=p2[j].coeff;
67 p3[k].expo=p2[j].expo;
68 j++;
69 k++;
70 }
71 return k;
72}
73
74void display(struct poly p[],int t){
75 int i;
76 for(i=0;i<t;i++){
77 printf("%dX^%d\t",p[i].coeff,p[i].expo);
78 if(i<t-1){
79 printf("+");
80 }
81 }
82 printf("\n");
83}
84
85