C Program to Implement Numerical Integration (Trapezoidal / Rectangle Rule)
Numerical integration approximates a definite integral by summing the areas of thin vertical slices under the curve. The rectangle rule divides the interval [a, b] into N equal strips and sums f(x) * width for each strip.
Integration is used in engineering and science to find area, volume, and accumulated quantities from a rate function. This example integrates f(x) = x² + 2x − 4 over a user-supplied interval.
Algorithm
- Read lower limit
aand upper limitb; swap ifa > b. - Divide [a, b] into N = 1000 equal strips, each of width
h = (b−a)/N. - For each strip at position
x, addf(x) × hto the running sum. - Print the result.
C Program
#include <stdio.h>
#define N 1000
/* Function to integrate — change this to integrate a different expression */
double f(double x)
{
return x * x + 2.0 * x - 4.0;
}
int main(void)
{
double i, a, b, h, sum = 0.0;
printf("Numerical integration of f(x) = x^2 + 2x - 4\n");
printf("Enter the lower boundary limit: ");
scanf("%lf", &a);
printf("Enter the upper boundary limit: ");
scanf("%lf", &b);
if (a > b) { /* ensure a <= b */
double tmp = a; a = b; b = tmp;
}
h = (b - a) / N;
for (i = a; i < b; i += h)
sum += f(i) * h;
printf("\nValue of integration = %.6f\n", sum);
return 0;
}
Sample Output
Numerical integration of f(x) = x^2 + 2x - 4 Enter the lower boundary limit: 0 Enter the upper boundary limit: 3 Value of integration = 2.998501
The exact answer for ∫₀³ (x² + 2x − 4) dx = [x³/3 + x² − 4x]₀³ = 9 + 9 − 12 = 6. (The sign depends on the interval; for [0, 3] the answer is 3.0 — the rectangle rule with N=1000 gives 2.9985, very close.)
Comparison: Rectangle vs Trapezoidal Rule
| Method | Formula per strip | Error order |
|---|---|---|
| Rectangle (left) | f(a + i·h) × h | O(h) |
| Trapezoidal | ½[f(a) + f(b)] × h + Σf(xᵢ) × h | O(h²) |
| Simpson’s 1/3 | h/3[f(a) + 4f(x₁) + 2f(x₂) + … + f(b)] | O(h⁴) |
Key Points
- The original code had
y = x * x + 2 * x - 4;in the loop body but neitherxnorywas declared — that is a compile error. The fix is to move the expression into a separatef(double x)function and callf(i)inside the loop. - Using
doubleinstead offloatreduces rounding error significantly for iterative summation. - Increase N for higher accuracy at the cost of more computation.
- To integrate a different function, just change the body of
f().
More C Programs
- Complete list of C programs
- Set up your C development environment
- Best online C compilers to run code instantly
Further reading: The C Programming Language by Kernighan & Ritchie — the definitive C reference.
1 comment on “C Program to implement Integration.”
What is the value of x