C Program: Numerical Integration
#include <stdio.h>
#include <math.h>
// Define the function to integrate
float f(float x) {
return x * x + 2 * x + 1; // Example: f(x) = x² + 2x + 1
// Trapezoidal Rule
float trapezoidal(float a, float b, int n) {
float h = (b - a) / n;
float sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
sum += 2 * f(a + i * h);
return (h / 2) * sum;
// Simpson's 1/3 Rule
float simpson(float a, float b, int n) {
if (n % 2 != 0) {
printf("Simpson's rule requires even number of intervals.\n");
return -1;
float h = (b - a) / n;
float sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
if (i % 2 == 0)
sum += 2 * f(a + i * h);
else
sum += 4 * f(a + i * h);
return (h / 3) * sum;
int main() {
float a, b;
int n;
// Input
printf("Enter the lower limit a: ");
scanf("%f", &a);
printf("Enter the upper limit b: ");
scanf("%f", &b);
printf("Enter the number of intervals n: ");
scanf("%d", &n);
// Trapezoidal Rule
float trap_result = trapezoidal(a, b, n);
printf("\nResult using Trapezoidal Rule: %.5f\n", trap_result);
// Simpson's Rule
float simp_result = simpson(a, b, n);
if (simp_result != -1)
printf("Result using Simpson's 1/3 Rule: %.5f\n", simp_result);
return 0;
Example Input:
Enter the lower limit a: 0
Enter the upper limit b: 2
Enter the number of intervals n: 4