33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to find the value of numerical integration by using/ Trapezoidal Rule/ Simpson’s one-third rule/ Simpson’s 3/8 rule.

Published on Dec 22, 2025
✔ Trapezoidal Rule✔ Simpson’s 1/3 Rule✔ Simpson’s 3/8 Rule
 

#include <iostream>
#include <cmath>
using namespace std;
// Function definition
double f(double x) {
    return 1 / (1 + x * x);
}

int main() {
    int choice, n;
    double a, b, h, sum = 0.0, result;

    cout << "Choose Method:\n";
    cout << "1. Trapezoidal Rule\n";
    cout << "2. Simpson's 1/3 Rule\n";
    cout << "3. Simpson's 3/8 Rule\n";
    cout << "Enter choice: ";
    cin >> choice;

    cout << "Enter lower limit a and upper limit b: ";
    cin >> a >> b;

    cout << "Enter number of subintervals n: ";
    cin >> n;

    h = (b - a) / n;

    switch (choice) {

    // -------- Trapezoidal Rule --------
    case 1:
        sum = f(a) + f(b);
        for (int i = 1; i < n; i++) {
            sum += 2 * f(a + i * h);
        }
        result = (h / 2) * sum;
        cout << "Integral value by Trapezoidal Rule = " << result << endl;
        break;

    // -------- Simpson's 1/3 Rule --------
    case 2:
        if (n % 2 != 0) {
            cout << "n must be even for Simpson's 1/3 Rule." << endl;
            return 0;
        }
        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);
        }
        result = (h / 3) * sum;
        cout << "Integral value by Simpson's 1/3 Rule = " << result << endl;
        break;

    // -------- Simpson's 3/8 Rule --------
    case 3:
        if (n % 3 != 0) {
            cout << "n must be a multiple of 3 for Simpson's 3/8 Rule." << endl;
            return 0;
        }
        sum = f(a) + f(b);
        for (int i = 1; i < n; i++) {
            if (i % 3 == 0)
                sum += 2 * f(a + i * h);
            else
                sum += 3 * f(a + i * h);
        }
        result = (3 * h / 8) * sum;
        cout << "Integral value by Simpson's 3/8 Rule = " << result << endl;
        break;

    default:
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

Documentation

Input

Choose Method:
1. Trapezoidal Rule
2. Simpson's 1/3 Rule
3. Simpson's 3/8 Rule
Enter choice: 2
Enter lower limit a and upper limit b: 0 1
Enter number of subintervals n: 4

 

Output

Integral value by Simpson's 1/3 Rule = 0.7854


Important Exam Notes

  • Trapezoidal Rule → simple, less accurate

  • Simpson’s 1/3 Rule → n must be even

  • Simpson’s 3/8 Rule → n must be multiple of 3

  • Accuracy:
    Simpson’s 1/3 > Simpson’s 3/8 > Trapezoidal

Problem Assumption

Let the function be:

f(x)=1 / 1+x2

Evaluate the integral between limits a and b.