/* road15.cpp uses the trapezoidal method to find the volume of
 *  dirt that must be removed to construct a road through a hill.
 *
 *  Input:  the length of roadway through the hill,
 *          the width of the roadway
 *  Output: the approximate volume of dirt removed
 *****************************************************************/

#include <iostream>             // cin, cout. >>, <<

double TrapezoidalArea(int n, double totalLength);

int main()
{

   cout << "Enter the length of roadway through the hill: ";
   double roadLength;                           // get the road length
   cin >> roadLength;

   cout << "Enter the number of points at which hill elevation "
           "was measured: ";
   int numPoints;
   cin >> numPoints;

   cout << "Enter the hill elevations (y values) at the " << numPoints 
        << " equally-spaced points.\n  The amount of dirt to be removed"
           " from the hill will be computed.\n\n";

                                                // compute X-sectional area
   double hillCrossSectionalArea = TrapezoidalArea(numPoints-1, roadLength);

   cout << "Enter the width of the roadway: ";
   double roadWidth;                            // get the road width
   cin >> roadWidth;
                                                // compute volume
   double dirtVolume = roadWidth * hillCrossSectionalArea;
                                                // display volume
   cout << "\n--> The volume of dirt to be removed is approximately "
       << dirtVolume << " cubic units." << endl;

   return 0;
}

/* TrapezoidalArea computes the approximate area under a curve for
 * which a collection of y values at equally spaced x values are
 * entered from the keyboard.
 *
 *   Receive:      n, number of subintervals along the x axis
 *                 intLength, the length of the interval on the x axis
 *   Precondition: the y values correspond to equally-spaced x values 
 *                 in the interval on the x axis.
 *   Return:       the approximate area under the curve
 ************************************************************************/

double TrapezoidalArea(int n, double intLength)
{
   double yValue;
   cout << "First y value? ";
   cin >> yValue;                         // the first y value
   double sum = yValue / 2.0;             // initialize sum to 1/2 of it

   for (int i = 1; i <= n - 1; i++) 
   {
      cout << "Next y value?  ";
      cin >> yValue;                      // i-th y value
      sum += yValue;                      // add it to sum
   }

   cout << "Last y value?  ";
   cin >> yValue;                         // the last y value
   sum += yValue/ 2.0;                    // add 1/2 of it to sum

   double deltaX = intLength / double(n);

   return deltaX * sum;                   // total area of trapezoids
}


