Saturday 28 September 2024

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


#include <stdio.h>


// Function to multiply two polynomials

void multiplyPolynomials(int poly1[], int poly2[], int result[], int n1, int n2) {

    // Multiply the two polynomials and store the result in the result array

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

        for (int j = 0; j < n2; j++) {

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

        }

    }

}


// 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

    }

    printf("\n");

}


int main() {

    int n1, n2, poly1[100], poly2[100];


    // Input for the first polynomial

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

    scanf("%d", &n1);


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

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

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

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

    }


    // Input for the second polynomial

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

    scanf("%d", &n2);


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

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

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

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

    }


    // Resultant polynomial will have degree (n1 + n2 - 2), hence n1 + n2 - 1 terms

    int result[200] = {0}; // Array for the result, initialized to 0


    // Multiply the two polynomials

    multiplyPolynomials(poly1, poly2, result, n1, n2);


    // Display the input polynomials and the resultant polynomial

    printf("First Polynomial: ");

    displayPolynomial(poly1, n1);


    printf("Second Polynomial: ");

    displayPolynomial(poly2, n2);


    printf("Resultant Polynomial after multiplication: ");

    displayPolynomial(result, n1 + n2 - 1);


    return 0;

}