Program code for polynomial addition using C

/*code for adding two polynomials. please avoid giving duplicate power term. you can enter term values (coefficient and power) in any order. this code is designed for sorting them in appropriate order */

#include<stdio.h>
#include<conio.h>
#include<alloc.h>


typedef struct Polynomial{

int coeff;
int powe;
struct Polynomial *next;
}pl;



pl *create();
pl *polyadd(pl *,pl *);
void bubblesort(pl *);
void disp(pl *);


void main()
{
pl *h1,*h2,*h3;
clrscr();

printf("\n\nEnter value for first polynomial : ");
h1=create();
printf("\n\nEnter value for second polynomial : ");
h2=create();

bubblesort(h1);
bubblesort(h2);

printf("\n\nFirst Polynomial is : ");
disp(h1);
printf("\n\nFirst Polynomial is : ");
disp(h2);
h3=polyadd(h1,h2);
printf("\n\nAdded result of two Polynomial is : ");
disp(h3);
getch();
}


pl *create()
{
pl *temp,*ptr,*h=NULL;
int v,u;
char ch;

while(1)
{
printf("Enter coefficient and power of the term : ");
scanf("%d %d",&v,&u);



temp=(pl*)malloc(sizeof(pl));
temp->coeff=v;
temp->powe=u;
temp->next=NULL;
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
fflush(stdin);
printf("Do you ghave more term (y/n) : ");
scanf("%c",&ch);
if(ch=='n' || ch=='N')
return h;
}
}


void disp(pl *h)
{
while(h->next!=NULL)
{
printf(" %dx^%d +",h->coeff,h->powe);
h=h->next;
}
printf("%dx^%d",h->coeff,h->powe);
}


void bubblesort(pl *h)
{
int v,u;
pl *ptr,*loc;
loc=h;
while(h!=NULL)
{

ptr=loc;
//printf("%d",ptr->val);
while(ptr->next->next!=NULL)
{
if(ptr->powe<ptr->next->powe)
{
v=ptr->powe;
u=ptr->coeff;
ptr->powe=ptr->next->powe;
ptr->coeff=ptr->next->coeff;
ptr->next->powe=v;
ptr->next->coeff=u;

}
ptr=ptr->next;
}
if(ptr->powe<ptr->next->powe)
{
v=ptr->powe;
u=ptr->coeff;
ptr->powe=ptr->next->powe;
ptr->coeff=ptr->next->coeff;
ptr->next->powe=v;
ptr->next->coeff=u;
}
h=h->next;
}
}


pl *polyadd(pl *h1,pl *h2)
{
pl *ptr,*temp,*h=NULL;

while(h1!=NULL && h2!=NULL)
{
if(h1->powe>h2->powe)
{
temp=h1;
h1=h1->next;
}
else if(h2->powe>h1->powe)
{
temp=h2;
h2=h2->next;
}
else
{
h1->coeff=h1->coeff+h2->coeff;
temp=h1;
h1=h1->next;
h2=h2->next;
}
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
}
if(h1!=NULL && h2==NULL)
ptr->next=h1;
if(h2!=NULL && h1==NULL)
ptr->next=h2;

return h;


}

Comments

Popular posts from this blog

Pascal Triangle using 2D array

JAVA program to add two distance