polynomial addition

// Polynomial Addition

#include<stdio.h>

#include<stdlib.h>

struct node

{

  int coef;

  int xp;

  struct node *next;

}*poly1,*poly2,*poly3;

void create(struct node *p)

{

  char ch;

  struct node *t;

  do

    {

      t=(struct node *)malloc(sizeof(struct node));

      printf("\n Enter the coefficient");

      scanf("%d",&t->coef);

      printf("\n Enter the exponential");

      scanf("%d",&t->xp);

      p->next=t;

      t->next=NULL;

      p=t;

      printf("\n Do u want to continue :(y/n)");

      scanf("%s",&ch);

    } while((ch=='y')||(ch== 'Y'));

}



void add_poly(struct node *p1,struct node *p2,struct node *p3)

{

  struct node *tmp;

  p1=p1->next;

  p2=p2->next;

  while((p1!=NULL)&&(p2!=NULL))

    {

      tmp=(struct node *)malloc(sizeof(struct node));

      p3->next=tmp;

      p3=tmp;

      if((p1->xp)>(p2->xp))

        {

 p3->coef=p1->coef;

 p3->xp=p1->xp;

 p1=p1->next;

}

      else if((p1->xp)<(p2->xp))

{

 p3->coef=p2->coef;

 p3->xp=p2->xp;

 p2=p2->next;

}

      else

{

 p3->coef=p1->coef+p2->coef;

 p3->xp=p1->xp;

 p1=p1->next;

 p2=p2->next;

        }

    }

  while(p1!=NULL)

    {

       tmp=(struct node *)malloc(sizeof(struct node));

       tmp->coef=p1->coef;

       tmp->xp=p1->xp;

       p1=p1->next;

       p3->next=tmp;

       p3=tmp;

    }

  while(p2!=NULL)

    {

       tmp=(struct node *)malloc(sizeof(struct node));

       p3->next=tmp;

       p3=tmp;

       p3->coef=p2->coef;

       p3->xp=p2->xp;

       p2=p2->next;

    }
  p3->next=NULL;

}

void display(struct node *p)

{

  p=p->next;

  while(p!=NULL)

    {

      printf("%dx^%d",p->coef,p->xp);

      p=p->next;

      if(p!=NULL)

        printf("+");

    }

}

int main(void)

{

  poly1=(struct node *)malloc(sizeof(struct node));

   poly2=(struct node *)malloc(sizeof(struct node));

   poly3=(struct node *)malloc(sizeof(struct node));

   printf("\n Enter the Polynomial 1");

   create(poly1);

   printf("\n Enter the Polynomial 2");

   create(poly2);

   printf("\n Poly-1 is:\n");

   display(poly1);

   printf("\n Poly-2 is:\n");

   display(poly2);

   add_poly(poly1,poly2,poly3);

   printf("\n The Resultant Polynomial after adding the poly1 & poly 2 is: \n");

   display(poly3);

   return(0);

}

Comments

Popular Posts