C Program to implement Integration.

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

  1. Read lower limit a and upper limit b; swap if a > b.
  2. Divide [a, b] into N = 1000 equal strips, each of width h = (b−a)/N.
  3. For each strip at position x, add f(x) × h to the running sum.
  4. 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 neither x nor y was declared — that is a compile error. The fix is to move the expression into a separate f(double x) function and call f(i) inside the loop.
  • Using double instead of float reduces 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

Further reading: The C Programming Language by Kernighan & Ritchie — the definitive C reference.

1 comment on “C Program to implement Integration.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>