/* polytester.cpp is a driver program to test function Polynomial().
 *
 * Output: the value of Polynomial() for polynomials of various degrees
 ***********************************************************************/

#include <iostream>
using namespace std;

double Polynomial(int degree, double x, double a, ...);
int main()
{
  cout // P(1.0) for P(x) = 2
       << Polynomial(0, 1.0, 2.0) << endl
       // P(1.0) for P(x) = 2 + 3x
       << Polynomial(1, 1.0, 2.0, 3.0) << endl
       // P(1.0) for P(x) = 2 + 3x + 4x^2
       << Polynomial(2, 1.0, 2.0, 3.0, 4.0) << endl
       // P(1.0) for P(x) = 2 + 3x + 4x^2 + 5x^3
       << Polynomial(3, 1.0, 2.0, 3.0, 4.0, 5.0) << endl;
  return 0;
}

/* Insert the #include directive and the definition
   of function Polynomial() from Code 2 here. */
/* Polynomial will evaluate a polynomial of any degree.
 *
 * Receive: the int degree, a real value x, and the real
 * coefficients a, ... of a polynomial
 * Return: the real value of the polynomial at x
 ********************************************************************/
#include <cstdarg>

double Polynomial(int degree, double x, double a, ...)
{
  double
    power_of_x = 1.0,     // powers of x
    nextCoef,             // next coefficient
    polyValue = a;        // polynomial's value at x

  va_list argList;

  va_start(argList, a); // argList begins after a

  for (int i = 1; i <= degree; i++)
    {
      power_of_x *= x; // i-th power of x
      nextCoef = va_arg(argList, double); // get the ith coefficient

      polyValue += nextCoef * power_of_x; // ith term of polynomial
    }

  va_end(argList); // clean up the list

  return polyValue;
}

