C code for adding two polynomials

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int coeff;
int power;
struct node*next;
};
void read_poly(struct node**,int,int);
void add_poly(struct node*,struct node *);
void display(struct node*);
struct node *head3=NULL;
void main()
{
struct node *head1=NULL;
struct node *head2=NULL;
int i,ele,num,no,no1;
clrscr();
printf("Enter the degree of polynomial:");
scanf("%d",&no);
printf("
Enter the coefficients for polynomial p1:
");
for(i=no;i>=0;i--)
{
printf("Enter the value of %dth co-efficient:",i);
scanf("%d",&ele);
read_poly(&head1,ele,i);
}
printf("
--------------------------------------------------");
printf("
Enter the degree of 2nd polynomial:");
scanf("%d",&no1);
printf("
Enter the coefficients for polynomial p2:
");
for(i=no1;i>=0;i--)
{
printf("Enter the value of %dth co-efficient:",i);
scanf("%d",&ele);
read_poly(&head2,ele,i);
}
printf("
First polynomial is:");
display(head1);

printf("
Second polynomial is:");
display(head2);

printf("

After addition of polynomial p1 and p2:
");
add_poly(head1,head2);
display(head3);
getch();
}
void read_poly(struct node **q,int num,int pow)
{
struct node*temp=*q,*extra;
if(*q==NULL)
{
*q=((struct node*)malloc(sizeof(struct node)));
(*q)->coeff=num;
(*q)->power=pow;
(*q)->next=NULL;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
extra=((struct node*)malloc(sizeof(struct node)));
extra->coeff=num;
extra->power=pow;
extra->next=NULL;
temp->next=extra;
}
}
void add_poly(struct node *q,struct node *r)
{


        while(r!=NULL || q!=NULL)
        {
            if(q->power == r->power)
            {
                read_poly(&head3,q->coeff+r->coeff,r->power);
                r=r->next;
                q=q->next;
            }
            else if(q->power < r->power)   // 2 is big
            {
                  read_poly(&head3,r->coeff,r->power);
                  r=r->next;
            }
            else if(q->power > r->power)
            {

                   read_poly(&head3,q->coeff,q->power);
                   q=q->next;

            }


        }

}
void display(struct node *q)
{
    printf("
");
    while(q!=NULL)
    {
        printf(" %dX^%d",q->coeff,q->power);
        q=q->next;
    }
    printf(" =0");
}


Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.