Write a ‘C’ program to accept two polynomials and find the addition of accepted polynomials.
#include <stdio.h>
#define MAX 100
// Structure to represent a term
typedef struct {
int coeff;
int exp;
} Term;
// Function to read polynomial
void readPoly(Term poly[], int *n) {
printf("Enter number of terms: ");
scanf("%d", n);
for (int i = 0; i < *n; i++) {
printf("Enter coefficient and exponent of term %d: ", i + 1);
scanf("%d %d", &poly[i].coeff, &poly[i].exp);
}
}
// Function to display polynomial
void displayPoly(Term poly[], int n) {
for (int i = 0; i < n; i++) {
printf("%dx^%d", poly[i].coeff, poly[i].exp);
if (i != n - 1)
printf(" + ");
}
printf("\n");
}
// Function to add two polynomials
int addPoly(Term p1[], int n1, Term p2[], int n2, Term result[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (p1[i].exp == p2[j].exp) {
result[k].coeff = p1[i].coeff + p2[j].coeff;
result[k].exp = p1[i].exp;
i++; j++; k++;
}
else if (p1[i].exp > p2[j].exp) {
result[k] = p1[i];
i++; k++;
}
else {
result[k] = p2[j];
j++; k++;
}
}
// Copy remaining terms
while (i < n1) {
result[k++] = p1[i++];
}
while (j < n2) {
result[k++] = p2[j++];
}
return k; // number of terms in result
}
int main() {
Term p1[MAX], p2[MAX], result[MAX];
int n1, n2, n3;
printf("Enter first polynomial:\n");
readPoly(p1, &n1);
printf("\nEnter second polynomial:\n");
readPoly(p2, &n2);
printf("\nFirst Polynomial: ");
displayPoly(p1, n1);
printf("Second Polynomial: ");
displayPoly(p2, n2);
n3 = addPoly(p1, n1, p2, n2, result);
printf("Resultant Polynomial after Addition: ");
displayPoly(result, n3);
return 0;
}
