C program for polynomial addition using structure

Description


This program implements polynomial addition. A structure array [], b[] and c[] is declared. The number of coefficients of both polynomials are read to the variables n1 and n2 respectively.  Then the coefficients and exponents of both the polynomials are read one by one to the arrays a[] and b[] using a for loop. Then the program uses while loop to find the sum of these polynomials and stores it in the array c[]. Then the result of the addition is displayed to the output screen. 

Program


// polynomial addition using structure c program

#include<stdio.h>
#include<conio.h>
struct poly
{
int exp;
int coef;
}a[10],b[10],c[10];
void main()
{
int n1,n2,n3,i,j,k;
printf("\nEnter the number of coefficients of polynomial A");
scanf("%d",&n1);
printf("\nEnter the coefficient and exponents\n\n");
for(i=0;i<n1;i++)
scanf("%d%d",&a[i].coef,&a[i].exp);
printf("\nEnter the number of coefficients of polynomial B");
scanf("%d",&n2);
printf("\nEnter the coefficientds and exponents\n\n");
for(i=0;i<n2;i++)
scanf("%d%d",&b[i].coef,&b[i].exp);
i=0;j=0;k=0;
while((i<n1)&(j<n2))
{
if(a[i].exp==b[j].exp)
{
c[k].exp=a[i].exp+b[j].exp;
c[k].coef =a[i].coef;
i++;
j++;
k++;
}
else if(a[i].exp>b[j].exp)
{
c[k].exp=a[i].exp;
c[k].coef=a[i].coef;
i++;
k++;
}
else
{
c[k].exp=b[j].exp;
c[k].coef=b[j].coef;
k++;
j++;
}
}
while(i<n1)
{
c[k].exp=a[i].exp;
c[k].coef=a[i].coef;
i++;
k++;
}
while(j<n2)
{
c[k].exp=b[j].exp;
c[k].coef=b[j].coef;
k++;
j++;
}
i=0;
printf("\nSum Poly...\n");
while(i<k)
{
printf("%dX^%d",c[i].coef,c[i].exp);
i++;
}
getch();
}

1 comment:

Anonymous said...

Polynomial addition using structure: http://www.programmingwala.com/2012/12/polynomial-addition-structure-c-program.html