// polynomial3.cpp
// Computes a polynomial, using an algorithm
// which minimizes the number of multiplications.
// More efficient than polynomial1.cpp.
// Requires coefficients to be input
// highest-order first.

#include <iostream>

int main()
{
   cout << "This program computes the value "
              << "of a polynomial with" << endl;
   cout << "coefficients and variable value "
              << "entered by the user." << endl;

   cout << "Enter the value of the variable x:>";
   double x;
   cin >> x;

   cout << "Enter the degree of the polynomial:>";
   int degree;
   cin >> degree;
   if ( degree < 0 )
   {
      cout << "Degree " << degree
           << " must be non-negative." << endl;
      return 1;
   }  // if

   // Cumulative sum of terms of polynomial:
   double polynomial = 0;

   // The polynomial will now be generated
   // by adding each successive coefficient
   // to polynomial and then multiplying the
   // by x after each coefficient is added.

   // Ask user for coefficients and compute
   // interim polynomial for each coefficient:
   for ( int order = degree; order >= 1; order-- )
   {
      // Ask user for the coefficient:
      cout << "Enter the value of the order-"
              << order << " coefficient:>";
      double coefficient;
      cin >> coefficient;

      // Add coefficient and multiply by x:
      polynomial = polynomial + coefficient;
      polynomial = polynomial * x;
   }  // for order

   // Ask user for the constant term and add it to polynomial:
   cout << "Enter the value of the "
              << "constant term:>";
   double constantTerm;
   cin >> constantTerm;
   polynomial = polynomial + constantTerm;

   // Output result:
   cout << "The value of the polynomial is "
            << polynomial << "." << endl;

   return 0;
}  // function main