Write a ‘C’ program to accept two polynomials and find the addition of accepted polynomials.

c programs


 Write a ‘C’ program to accept two polynomials and find the addition of accepted polynomials.


#include <stdio.h>

// Function to add two polynomials and store the result in the third polynomial
void addPolynomials(int poly1[], int poly2[], int n1, int n2, int resultPoly[]) {
    int i, j, k;
    i = j = k = 0;

    while (i < n1 && j < n2) {
        if (poly1[i] > poly2[j]) {
            resultPoly[k++] = poly1[i++];
        } else if (poly1[i] < poly2[j]) {
            resultPoly[k++] = poly2[j++];
        } else {
            resultPoly[k] = poly1[i] + poly2[j];
            k++;
            i++;
            j++;
        }
    }

    while (i < n1) {
        resultPoly[k++] = poly1[i++];
    }

    while (j < n2) {
        resultPoly[k++] = poly2[j++];
    }
}

// Function to display the polynomial in a readable format
void displayPolynomial(int poly[], int n) {
    for (int i = 0; i < n; i++) {
        if (i == n - 1) {
            printf("%dx^%d", poly[i], i);
        } else {
            printf("%dx^%d + ", poly[i], i);
        }
    }
    printf("\n");
}

int main() {
    int n1, n2;

    printf("Enter the degree of the first polynomial: ");
    scanf("%d", &n1);

    int poly1[100];
    printf("Enter the coefficients of the first polynomial terms from highest to lowest degree:\n");
    for (int i = n1; i >= 0; i--) {
        scanf("%d", &poly1[i]);
    }

    printf("Enter the degree of the second polynomial: ");
    scanf("%d", &n2);

    int poly2[100];
    printf("Enter the coefficients of the second polynomial terms from highest to lowest degree:\n");
    for (int i = n2; i >= 0; i--) {
        scanf("%d", &poly2[i]);
    }

    int resultDegree = (n1 > n2) ? n1 : n2;
    int resultPoly[100];

    addPolynomials(poly1, poly2, n1 + 1, n2 + 1, resultPoly);

    printf("First polynomial: ");
    displayPolynomial(poly1, n1 + 1);

    printf("Second polynomial: ");
    displayPolynomial(poly2, n2 + 1);

    printf("Sum of the two polynomials: ");
    displayPolynomial(resultPoly, resultDegree + 1);

    return 0;
}

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.