Monday 9 September 2024

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

 #include <iostream>

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

   {

        std::cout << poly[i];

        if (i != 0)

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

        if (i != n - 1)

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

        

    }

    std::cout << std::endl;

}


int main() 

{

    int n; // Degree of the polynomial + 1

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

     std::cin >> n;


    int poly1[100], poly2[100], result[100]; 

// Arrays for the two polynomials and the result


    // Input for the first polynomial

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

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

      {

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

         std::cin >> poly1[i];

    }


    // Input for the second polynomial

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

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

    {

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

         std::cin >> poly2[i];

    }


    // Add the two polynomials

    addPolynomials(poly1, poly2, result, n);


    // Display the result

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

   displayPolynomial(poly1, n);


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

    displayPolynomial(poly2, n);


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

    displayPolynomial(result, n);

     getch();

    return 0;

}