Search Tutorials

Tuesday 23 April 2013

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("\nEnter the coefficients for polynomial p1:\n");
for(i=no;i>=0;i--)
{
printf("Enter the value of %dth co-efficient:",i);
scanf("%d",&ele);
read_poly(&head1,ele,i);
}
printf("\n--------------------------------------------------");
printf("\nEnter the degree of 2nd polynomial:");
scanf("%d",&no1);
printf("\nEnter the coefficients for polynomial p2:\n");
for(i=no1;i>=0;i--)
{
printf("Enter the value of %dth co-efficient:",i);
scanf("%d",&ele);
read_poly(&head2,ele,i);
}
printf("\nFirst polynomial is:");
display(head1);

printf("\nSecond polynomial is:");
display(head2);

printf("\n\nAfter addition of polynomial p1 and p2:\n");
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("\n");
    while(q!=NULL)
    {
        printf("\t%dX^%d",q->coeff,q->power);
        q=q->next;
    }
    printf("\t=0");
}


No comments:

Post a Comment

Back to Top