Polynomial
Polynomial, expression consisting of any number of terms,
each of which contains a constant, called a coefficient, and one or more
variables raised to an integral (whole number) power, as Exponent.
ex. 2x2 + 3x + 8.
#include <stdio.h>
#include <conio.h>
struct
poly
{
int
coff;
int
exp;
struct
poly *next;
};
typedef
struct poly pol;
pol*
Insert(pol *start,float co, int ex)
{
pol
*temp,*pr;
int
fl=0;
for(pr=start;pr!=NULL;pr=pr->next)
{
if(ex==pr->exp)
{
pr->coff=co+pr->coff;
return
start;
}
}
temp=(pol
*)malloc(sizeof(pol)); ;
temp->coff=co;
temp->exp=ex;
if(start==NULL)
{
start=temp;
temp->next=NULL;
}
else
{
for(pr=start;pr->next!=NULL;pr=pr->next);
pr->next=temp;
temp->next=NULL;
}
return
start;
}
pol*
polyadd(pol *start,pol *start1)
{
pol
*pr,*ptr;
pol
*PD=NULL;
int
cf,ex,cff=0,f;
for(pr=start;pr!=NULL;pr=pr->next)
{
cf=pr->coff;
ex=pr->exp;
f=0;
for(ptr=start1;ptr!=NULL;ptr=ptr->next)
{
if(pr->exp==ptr->exp)
{
cff=cf+ptr->coff;
f=1;
}
}
if(f==1)
{
PD=Insert(PD,cff,pr->exp);
}
else
PD=Insert(PD,cf,pr->exp);
}
for(ptr=start1;ptr!=NULL;ptr=ptr->next)
{ f=0;
for(pr=start;pr!=NULL;pr=pr->next)
{
if(ptr->exp==pr->exp)
{
f=1;
}
}
if(f==0)
{
PD=Insert(PD,ptr->coff,ptr->exp);
}
}
return PD;
}
void
display(pol *start)
{
pol
*pr;
for(pr=start;pr!=NULL;pr=pr->next)
{
printf("%dx^%d",
pr->coff,pr->exp);
if(pr->next!=NULL)
{
printf("+");
}
}
}
void
main()
{
int
choice,ch,co,ex;
pol
*head,*head1,*head2;
head=head1=head2=NULL;
clrscr();
while(choice!=4)
{
printf("\n\n\t1.
Insert");
printf("\n\t2.
Display");
printf("\n\t3.
Add");
printf("\n\t4.
Exit");
printf("\n\tEnter
a Choice : ");
scanf("%d",&choice);
switch(choice)
{
case
1:
printf("\n\tPoly
1 or 2?\t");
scanf("%d",&ch);
printf("\n\tEnter
Co-eff : ");
scanf("%d",&co);
printf("\n\tEnter
Exp. : ");
scanf("%d",&ex);
switch(ch)
{
case
1:
head=Insert(head,co,ex);
break;
case
2:
head1=Insert(head1,co,ex);
break;
default:
printf("\n\t*Invalid
Input*");
}
break;
case
2:
printf("\n\t1.
Poly-1");
printf("\n\t2.
Poly-2");
printf("\n\t3.
Final Poly?\t");
scanf("%d",&ch);
switch(ch)
{
case
1:
printf("\n\tFirst
Poly : ");
display(head);break;
case
2:
printf("\n\tSecond
Poly : ");
display(head1);break;
case
3:
printf("\n\tResulatant
Poly : ");
display(head2);break;
}
break;
case
3:
head2=polyadd(head,head1);break;
case
4:
printf("\n\tQuit....");
getch();
free(head);
free(head1);
free(head2);
exit(0);
}
}
}