# Various operations on polynomials using structures C Program

/* Various operations on polynomials using structures. */

#include<math.h>
#include<stdio.h>
#include<conio.h>
typedef struct term
{
int power;
float coeff;
}term;
typedef struct polynomial
{
term a[20];
int n;
}polynomial;
void init(polynomial *ptr);
void print(polynomial *ptr);
polynomial multiply(polynomial *p1,polynomial *p2);
float evaluate(polynomial *p1,float x);
void insert(polynomial *,term);
void main()
{
polynomial P1,P2,P3;
int option;
float x,value;
do
{
printf("\n1 : create 1'st polynomial");
printf("\n2 : create 2'nd polynomial");
printf("\n4 : Multiply polynomials");
printf("\n5 : Evaluate 1'st polynomial");
printf("\n6 : Quit");
scanf("%d",&option);
switch(option)
{
printf("\n1'st polynomial -> ");
print(&P1);
printf("\n2'nd polynomial -> ");
print(&P2);
printf("\n Sum = ");
print(&P3);
break;
case 4:P3=multiply(&P1,&P2);
printf("\n1'st polynomial -> ");
print(&P1);
printf("\n2'nd polynomial -> ");
print(&P2);
printf("\n Product = ");
print(&P3);
break;
case 5:printf("\nEnter the value of x:");
scanf("%f",&x);
value=evaluate(&P1,x);
printf("\nValue of Polynomial =%6.2f",value);
break;
}
}while(option!=6);
}
{
int n, i, power;
float coeff;
term t;
init(Ptr);
printf("\n Enter number of terms :");
scanf("%d",&n);
for (i=0;i<n;i++)
{       printf("\nenter a term(power  coeff.)");
scanf("%d%f",&power,&coeff);
t.power=power;
t.coeff=coeff;
insert(Ptr,t);
}
}
void print(polynomial *Ptr)
{
int i;
printf("%5.2fX^%d ",(Ptr->a[0]).coeff,(Ptr->a[0]).power);
for(i=1;i<Ptr->n;i++)
printf(" + %5.2fX^%d ",(Ptr->a[i]).coeff,(Ptr->a[i]).power);
}
{
polynomial P3;
term t;
int i,j;
i=j=0;
init(&P3);
while(i<P1->n && j<P2->n)
{
if(P1->a[i].power==P2->a[j].power)
{
t.power=P1->a[i].power;
t.coeff=P1->a[i].coeff+P2->a[j].coeff;
insert(&P3,t);
i++;j++;
}
else
if(P1->a[i].power < P2->a[j].power)
{
insert(&P3,P1->a[i]);
i++;
}
else
{
insert(&P3,P2->a[j]);
j++;
}
}
while(i<P1->n)
{
insert(&P3,P1->a[i]);
i++;
}
while(j<P2->n)
{
insert(&P3,P2->a[j]);
j++;
}
return(P3);
}
polynomial multiply(polynomial *P1,polynomial *P2)
{
polynomial P3, Ptemp;
term t;
int i,j;
init(&P3);
for(i=0;i<P2->n;i++)
{
init(&Ptemp);
for(j=0;j<P1->n;j++)
{
t.power=P1->a[j].power+P2->a[i].power;
t.coeff=P1->a[j].coeff*P2->a[i].coeff;                                        insert (&Ptemp, t);
}
}
return(P3);
}
float evaluate(polynomial *P, float x)
{
float value;
int i,power;
value=0.00;
for(i=0;i<P->n;i++)
{ power=P->a[i].power;
value=value+(P->a[i].coeff)*pow(x,power);
}
return(value);
}
void init(polynomial *Ptr)
{
Ptr->n=0;
}
void insert(polynomial *Ptr,term t)
{
int i;
/* move all higher power term by 1 place.movement