Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

#include <stdio.

h>

#define MAX_TERMS 100 // Maximum number of terms in the polynomial

Typedef struct {

Int coef; // Coefficient of the term

Int exp; // Exponent of the term

} term;

// Function to read a polynomial from the user

Void read_polynomial(term poly[]) {

Int n;

Printf(“Enter the number of terms in the polynomial: “);

Scanf(“%d”, &n);

Printf(“Enter the coefficient and exponent of each term:\n”);

For (int I = 0; I < n; i++)

Printf(“Term %d: “, i+1);

Scanf(“%d %d”, &poly[i].coef, &poly[i].exp);

// Function to add two polynomials

Void add_polynomials(term poly1[], term poly2[], term result[])

Int I = 0, j = 0, k = 0;

While (poly1[i].coef != 0 || poly2[j].coef != 0)

If (poly1[i].exp == poly2[j].exp)

Result[k].coef = poly1[i].coef + poly2[j].coef;

Result[k].exp = poly1[i].exp;
I++;

J++;

Else if (poly1[i].exp > poly2[j].exp)

Result[k].coef = poly1[i].coef;

Result[k].exp = poly1[i].exp;

I++;

Else {

Result[k].coef = poly2[j].coef;

Result[k].exp = poly2[j].exp;

J++;

K++;

// Function to display a polynomial

Void display_polynomial(term poly[])

Int I = 0;

While (poly[i].coef != 0)

Printf(“%dx^%d “, poly[i].coef, poly[i].exp);

If (poly[i+1].coef != 0) {

Printf(“+ “);

I++;

}
Printf(“\n”);

// Main function

Int main() {

Term poly1[MAX_TERMS], poly2[MAX_TERMS], result[MAX_TERMS];

Printf(“Enter the first polynomial:\n”);

Read_polynomial(poly1);

Printf(“Enter the second polynomial:\n”);

Read_polynomial(poly2);

Add_polynomials(poly1, poly2, result);

Printf(“The sum of the two polynomials is:\n”);

Display_polynomial(result);

Return 0;

You might also like