Saturday, August 9, 2014

Program for polynomial addition

This is a program for polynomial addition. Please be sure to enter the coefficients in the decreasing order of power. Comment below if you need help
#include<stdio.h> struct node { int coef; int pow; struct node *link; }*poly,*poly1=NULL,*poly2=NULL,*node,*next; void polcreate(struct node *next) { int ch; do { printf("\nCoeff of the term?"); scanf("%d",&next->coef); printf("\nPower of the term?"); scanf("%d",&next->pow); next->link=(struct node*)malloc(sizeof(struct node)); next=next->link; printf("\nEnter 1 to continue press 2 to terminate the expression : "); scanf("%d",&ch); }while(ch==1); } void show(struct node *next) { while(next->link!=NULL) { printf("%dX^%d",next->coef,next->pow); next= next->link; if( next->link!=NULL) printf("+"); } printf("\n"); } void polyadd(struct node *poly1,struct node *poly2,struct node *poly) { while(poly1->link && poly2->link) { if(poly1->pow > poly2->pow) { poly->pow= poly1->pow; poly->coef= poly1->coef; poly1= poly1->link; } else if(poly1->pow < poly2->pow) { poly->pow= poly2->pow; poly->coef= poly2->coef; poly2= poly2->link; } else { poly->pow= poly1->pow; poly->coef= poly1->coef + poly2->coef; poly1= poly1->link; poly2= poly2->link; } poly->link= (struct node*)malloc(sizeof(struct node)); poly=poly->link; poly->link=NULL; } while(poly1->link||poly2->link) { if(poly1->link) { poly->pow=poly1->pow; poly->coef=poly1->coef; poly1= poly1->link; } if(poly2->link) { poly->pow= poly2->pow; poly->coef= poly2->coef; poly2= poly2->link; } poly->link= (struct node*)malloc(sizeof(struct node)); poly = poly->link; poly->link=NULL; } } int main() { poly1=(struct node*)malloc(sizeof(struct node)); poly2=(struct node*)malloc(sizeof(struct node)); poly=(struct node*)malloc(sizeof(struct node)); printf("\nPOLYNOMIAL 1(decreasing order of power)\n"); polcreate(poly1); printf("\nPOLYNOMIAL 2(decreasing order of power)\n"); polcreate(poly2); printf("\nFirst polynomial : \n"); show(poly1); printf("Second polynomial : \n"); show(poly2); polyadd(poly1,poly2,poly); printf("\n sum is as follows\n"); show(poly); }

No comments:

Post a Comment