Monday 9 September 2024

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

 


#include <iostream>


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

    {

        std::cout << poly[i];

        if (i != 0)

            std::cout << "x^" << i; // Display power of x

        if (i != n - 1)

            std::cout << " + "; // Display '+' between terms

    }

    std::cout << std::endl;

}


int main()

{

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


    // Input for the first polynomial

    std::cout << "Enter the number of terms in the first polynomial: ";

    std::cin >> n1;


    std::cout << "Enter the coefficients of the first polynomial:\n";

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

    {

        std::cout << "Coefficient of x^" << i << ": ";

        std::cin >> poly1[i];

    }


    // Input for the second polynomial

    std::cout << "Enter the number of terms in the second polynomial: ";

    std::cin >> n2;


      std::cout << "Enter the coefficients of the second polynomial:\n";

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

    {

        std::cout << "Coefficient of x^" << i << ": ";

        std::cin >> 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

    std::cout << "First Polynomial: ";

    displayPolynomial(poly1, n1);


    std::cout << "Second Polynomial: ";

    displayPolynomial(poly2, n2);


    std::cout << "Resultant Polynomial after multiplication: ";

    displayPolynomial(result, n1 + n2 - 1);


    return 0;

}