Answer to Question #196358 in C++ for Jaydon

Question #196358

A. write pseudocode algorithm to determine the integral of a function between two specified points using the rectangular rule. B. write C++ computer programs to determine the integral of a function between two specified points using the rectangular rule


1
Expert's answer
2021-05-21T00:01:48-0400
#include <iostream>
#include <cmath>

using namespace std;

/*
 * f   - pointer to function, 
 * a,b - borders, where a < b,
 * n   - number of rectangles.
 */
double integrate(double (*f)(double), double a, double b, int n)
{
    double x, y, area = 0.0;
    /* h - step */
    double h = (b - a) / n;
    for (int i = 0; i < n; i++) {
        x = a + i * h;
        y = a + (i + 1) * h;
        area += h * f(0.5 * (x + y));
    }
    return area;
}

int main() 
{
    auto func = [](double x) {
        return sin(x) + cos(x);
    };
    cout << "integrate: sin(x) + cos(x)\n";
    double a, b;
    int n;
    cout << "lower_bound(a): ";
    cin >> a;
    cout << "upper_bound(b): ";
    cin >> b;
    cout << "number_of_reactangles: ";
    cin >> n;
    cout << "I=" << integrate(func, a, b, n);
    return 0;    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog