Do you want to know in general, or do you have a particular algorithm in mind?
One simple way is:
Code:
#include <stdio.h>
#include <math.h>
double f(double x) {
return 1.0 + exp(x);
}
/* Integrates f from a to b, using n intervals. */
double integrate(double (*f)(double), double a, double b, int n) {
double interval_size = (b - a) / n;
double x = a + interval_size * 0.5;
double ret = 0.0;
while (n--) {
ret += (*f)(x);
x += interval_size;
}
ret *= interval_size;
return ret;
}
int main(void) {
int i;
puts("Approximations of the area underneath 1+e^x from 0 to 1:");
for (i = 1; i <= 20; ++i) {
printf("%d intervals: %f\n", i, integrate(&f, 0.0, 1.0, i));
}
return 0;
}
This is known as the 'midpoint method,' and is relatively well-known. There are many more sophisticated general numeric integration algorithms; this is about the simplest you'll find. Don't forget about floating point error.
For some popular functions, there exist specialized formulas that approximate the integral extremely well. For example, the normal curve has a whole slew of specialized formulas that are much more efficient than naive integration. So you might want to look around for those if you have a peculiar function in mind.