Saturday 28 September 2024

Write a Program to implement addition of two polynomials using 1 dimensional array.

 


#include <stdio.h>

#include <conio.h>


// Function to add two polynomials

void addPolynomials(int poly1[], int poly2[], int result[], int n) {

    for (int i = 0; i < n; i++) {

        result[i] = poly1[i] + poly2[i];

    }

}


// Function to display a polynomial

void displayPolynomial(int poly[], int n) {

    for (int i = 0; i < n; i++) {

        printf("%d", poly[i]);

        if (i != 0) {

            printf("x^%d", i); // Display power of x

        }

        if (i != n - 1) {

            printf(" + "); // Display '+' between terms in result

        }

    }

    printf("\n");

}


int main() {

    int n; // Degree of the polynomial + 1

    printf("Enter the number of terms in the polynomials: ");

    scanf("%d", &n);


    int poly1[100], poly2[100], result[100]; // Arrays for the two polynomials and the result


    // Input for the first polynomial

    printf("Enter the coefficients of the first polynomial:\n");

    for (int i = 0; i < n; i++) {

        printf("Coefficient of x^%d: ", i);

        scanf("%d", &poly1[i]);

    }


    // Input for the second polynomial

    printf("Enter the coefficients of the second polynomial:\n");

    for (int i = 0; i < n; i++) {

        printf("Coefficient of x^%d: ", i);

        scanf("%d", &poly2[i]);

    }


    // Add the two polynomials

    addPolynomials(poly1, poly2, result, n);


    // Display the polynomials and the result

    printf("First Polynomial: ");

    displayPolynomial(poly1, n);


    printf("Second Polynomial: ");

    displayPolynomial(poly2, n);


    printf("Resultant Polynomial after addition: ");

    displayPolynomial(result, n);


    getch(); 

    return 0;

}