Write a C code to add two polynomials having two numbers of unknown variables.
#include <stdio.h>
#include <stdlib.h>
#define MAXDEGREE 90
typedef struct
{
int deg;
int coef[MAXDEGREE];
} poly;
int main()
{
poly polynomialA;
poly polynomialB;
int i,j, maxdeg;
int terminator;
printf("\nPolynomial Additon\n");
printf("Enter the number of degrees of first polynomial: ");
scanf("%d", &polynomialA.deg);
printf("\nEnter the number of degrees of first polynomial: ");
scanf("%d", &polynomialB.deg);
if(polynomialA.deg > polynomialB.deg) {
maxdeg = polynomialA.deg;
} else if (polynomialA.deg < polynomialB.deg) {
maxdeg = polynomialB.deg;
} else {
maxdeg = polynomialA.deg;
}
printf("\nEnter all the coefficients of the first polynomial. Starting from the coefficient of the largest power");
printf("\n\n");
for(i=0; i<=maxdeg; i++) {
scanf("%d", &polynomialA.coef[i]);
}
printf("\nEnter all the coefficients of the second polynomial. Starting from the coefficient of the largest power");
for(j=0; j<=maxdeg; j++) {
scanf("%d", &polynomialB.coef[j]);
}
printf("\n\n...");
addpolynomials(polynomialA, polynomialB);
scanf("%d", &terminator);
return 0;
}
void addpolynomials(poly a, poly b)
{
poly c;
int y,z;
int maxdeg;
if(a.deg > b.deg) {
maxdeg = a.deg;
} else
{
maxdeg = b.deg;
}
c.deg = maxdeg;
for(y =0; y <= maxdeg; y++) {
c.coef[y] = a.coef[y] + b.coef[y];
}
printf("The sum of the two polynomial is: \n");
for(z = 0; z<=maxdeg; z++) {
printf("%i ", c.coef[z]);
}
}
Comments
Leave a comment