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

#include <stdio.h>
#include <math.h>

const int n = 50;          /* number of subintervals to be used */

/* function to be used in the area approximation
 *  Preconditions: x*x does not underflow or overflow
 *  Postconditions: f(x) = sqrt(4-x^2) 
 */
double f(double x);

/* Approximation of area under f(x) on [a, b] using the Trapezoidal Rule
 * 
 * Preconditions: 
 *  b > a
 *  numInt > 0
 *
 * Postconditions:
 *  *area modified to contain the calculated area
 */
void compute_area(double a, double b, int numInt, double *area);

/* main: runs trapezoid approximation for semicircle of radius 2 centered at
 * origin over [0,2] 
 * 
 * Preconditions: 
 *  f(x) is defined
 *  compute_area is defined
 *
 * Postconditions: 
 *  Prints the area to terminal
 *  returns 0
 */
int main (void)
{  double new_area;
   printf ("Program approximates the area under a function using the ");
   printf ("Trapezoidal Rule, based on %d intervals.\n", n);

   compute_area(0.0, 2.0, n, &new_area);
   printf ("The approximate area is %7.4f\n", new_area);

   return 0;
}

/* function to be used in the area approximation
 *  Preconditions: x*x does not underflow or overflow
 *  Postconditions: f(x) = sqrt(4-x^2) 
 */
double f(double x) 
{
  return sqrt(4.0 - x*x);
}

/* Approximation of area under f(x) on [a, b] using the Trapezoidal Rule
 * 
 * Preconditions: 
 *  b > a
 *  numInt > 0
 *
 * Postconditions:
 *  *area modified to contain the calculated area
 */ 
void compute_area (double a, double b, int numInt, double *area)
{
  double width = (b - a) / (double) numInt; 
  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;
}
