#include <stdio.h>
#include <math.h>

/* Program to perform numerical integration using the trapezoidal rule on
the function defined in int_func */

double calc_area (double,  double);
/* Calculate the area of a trapezium */

double int_func (double);
/* The function which we are calculating the integeral of */

int main(int argc, char **argv)
{
	int i;
    int no_trap;   /* No. of segments to use */
    double area= 0;  // Area under curve
    double x;		// Postion currently being considered
	double xlow= 0.0;  // Lower limit of integral
	double xup= 2.0;   // Upper limit of integral
	double width;		// Width of a trapezium

	// Try various numbers of trapeziums
	for (no_trap= 2; no_trap <= 100; no_trap++) { 
		printf ("Performing calculation for %d trapeziums\n",no_trap);
		x= xlow;	// Start at the lower limit 
		width= (xup-xlow)/no_trap;
		area= 0;
		// Add on area of each of no_trap trapeziums
		for (i= 0; i < no_trap; i++) {
			area+= calc_area(x, x+width);
			x+= width;
		}
		printf ("The estimate for the integral is %f.\n",area);

    }
    return 0;
}

double calc_area (double xmin, double xmax)
/* Calculates the area of a trapezium with base running from
xmin to xmax */
{
	double area;
    double width=(xmax-xmin);
	// Area of trap is width * average height
	area= width * (int_func(xmin) + int_func(xmax))/2.0;
    return area;
}

double int_func (double x)
/* The function we are taking the integral of - in this case cos(x)e^x*/
{
    return (cos(x)*exp(x));
}

