// Approximating the area under sqrt(4-x^2) on [0, 2] using the Trapezoidal Rule.
// Version 3:  A procedure performs the area computation.

#include <iostream.h>
#include <math.h>

double f(double x);
/* function to be used in the area approximation */

void compute_area(double a, double b, int n, double &area);
/* Approximation of area under f(x) on [a, b] using the Trapezoidal Rule */

int main (void)
{  int n;
   double area;
   cout << "Program approximates the area under a function using the "
        << "Trapezoidal Rule." << endl;
   cout << "Enter number of subintervals to be used: ";
   cin  >> n;

   compute_area(0.0, 2.0, n, area);
   cout << "The approximate area is " << area << endl;
   return 0;
}

double f(double x) 
/* function to be used in the area approximation */
{  return (sqrt(4.0 - x*x));
}
 
void compute_area (double a, double b, int n, double &area)
/* Finding area via the Trapezoidal Rule */
{  double width = (b - a) / (double) n; 
   double sum = (f(a) + f(b)) / 2.0;   /* first and last terms in sum */
   double xvalue;

   for (xvalue = a + width; xvalue < b; xvalue += width)
      sum += f(xvalue);
 
   area = sum * width;
}
