Sunday, 24 December 2017

Write a program in C language to add two Polynomials.

Below is a picture which shows the working of the addition of two polynomials.

Implementation of the above problem:
#include<stdio.h>
void main()
{
int c1[10],e1[10],c2[10],e2[10],i,rc[20],re[20],n,m,k,l,j;
clrscr();
printf("Enter the highest index of 1st Polynomial : ");
scanf("%d",&n);
for(i=n;i>=0;i--)
{
printf("Enter the coefficient of x^%d : ",i);
scanf("%d",&c1[i]); e1[i]=i;
}
printf("Enter the highest index of 2nd Polynomial : ");
scanf("%d",&m);
for(i=m;i>=0;i--)
{
printf("Enter the coefficient of x^%d : ",i);
scanf("%d",&c2[i]); e2[i]=i;
}
printf("\nThe first Polynomial is : \n");
for(i=n;i>=0;i--)
{
printf("%d x^%d",c1[i],e1[i]);
if(i>0) printf(" + ");
}
printf("\nThe second Polynomial is : \n");
for(i=m;i>=0;i--)
{
printf("%d x^%d",c2[i],e2[i]);
if(i>0) printf(" + ");
}
k=n; l=m; j=0;
while(k>=0 && l>=0)
{
if(k>=0 || l>=0)
{
if(e1[k]==e2[l])
{
rc[j]=c1[k]+c2[l]; re[j]=e1[k];
j=j+1; k=k-1; l=l-1;
}
else if(e1[k]>e2[l])
{
rc[j]=c1[k]; re[j]=e1[k]; j=j+1; k=k-1;
}
else if(e1[k]<e2[l])
{
rc[j]=c2[l]; re[j]=e2[l]; j=j+1; l=l-1;
}
}
else if (k==0 && l>0)
{
rc[j]=c2[l]; re[j]=e2[l]; j=j+1; l=l-1;
}
else if(k>0 && l==0)
{
rc[j]=c1[k]; re[j]=e1[k]; j=j+1; k=k-1;
}
}
printf("\nThe Sum of the two Polynomials is : \n");
j=j-1;
for(i=0;i<=j;i++)
{
printf("%d x^%d",rc[i],re[i]);
if(i<j) printf(" + ");
}
getch();
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput