Search This Blog

Sunday, October 9, 2011

MCS-021 Assignments Solution January-2012:-Question 1Write a program for multiplication of two polynomials. Use Doubly Linked lists. (20 marks)


struct d_list{
int coeff;
int exp;
struct d_list *left;
struct d_list *right;
};
typedef struct d_list poly;
void poly_create(poly*);




void poly_display(poly*);
void poly_multiply(poly*,poly*);
/* Function to create a polynomial */
void poly_create(poly *start)
{
int ch;
printf("\nPress 0 to exit :");
scanf("%d",&ch);
switch(ch)
{
default:
{
                     printf("Input the values of polynomial in the format
<coeff>,<exponent>\n");
scanf("%d,%d",&start->coeff,&start->exp);
if(start->coeff !=0)
{
start->right=(poly*)malloc(sizeof(poly));
start->right->left=start;
start->right->right=NULL;
poly_create(start->right);
}
else
{
start->right=NULL;
}
}



case 0:break;
}
}
/*Function to display polynomial */
void poly_display(poly *head,int i)
{
if(i==1)
{
printf("\nDisplaying %dst Polynomial using Right pointer:\n",i);
}
else
{
printf("\nDisplaying %dnd Polynomial using Right pointer:\n",i);
}
do{
printf("%d x^%d\t",head->coeff,head->exp);
head=head->right;
}while(head->right);
}
/* Function to Multiply Polynomials */
void poly_multiply(poly *p1,poly *p2)
{
poly *temp;



for(;p1->right!=NULL;p1=p1->right){
for(temp=p2;temp->right!=NULL;temp=temp->right){
printf("%d x^",(p1->coeff) * (temp->coeff));
printf("%d\t",(p1->exp) + (temp->exp));
}
}
}
void main()
{
poly *first,*second;
printf("A program to multiply two polynomials using Doubly Linked List\n\n");
printf("\nEnter First Polynomial");
first=(poly*)malloc(sizeof(poly));
first->left=NULL;
first->right=NULL;
poly_create(first);
poly_display(first,1);
printf("\nEnter Second Polynomial");
second=(poly*)malloc(sizeof(poly));



second->left=NULL;
second->right=NULL;
poly_create(second);
poly_display(second,2);
printf("\nDisplaying Both Polynomials and product:\n\n");
poly_display(first,1);
poly_display(second,2);
printf("\n\nProduct of above polynomials:\n");
poly_multiply(first,second);
printf("\n");
}


No comments:

Post a Comment