Help with an array involving integration?

• 04-10-2010
gulfx01
Help with an array involving integration?
I am having trouble solving this problem with an array. Here are the instructions:

You will write a program that evaluates the integral of sin(x) using the left-hand rectangle rule with
2000 subintervals, over 10 intervals. The intervals to test are [0, 1), [1, 2), …, [8, 9), [9, 10). You will
declare an array of type double that can hold 10 elements, and you will use this array to hold all 10
results you get from evaluating each interval.
Once you have calculated the integral as described for each interval, and the results are all stored in
your array, you will sort the array from smallest to largest, and output each element on separate lines.

Here is my code, although I know a lot of it is incorrect.

Code:

``` #include <iostream> #include <iomanip> #include <cmath> using namespace std; double integrate(double a, double b, int n); double f(double x); int main () { const int ARRAY_SIZE = 10; int numbers[ARRAY_SIZE]; int count; for(count=0; count < 10; count ++) cout << f(numbers[count]) << endl; } double integrate(double x1, double x2, int n) { double sum = 0, base; base = (x2-x1)/n; { sum = sum + f(x1); x1 = x1 + base; } return sum*base; } double f(double x) { return sin(x); }```
// I know that it is probably incorrect, can someone fix my code or help me out please? I am also having big problems sorting the values.
• 04-10-2010
NeonBlack
It looks like you're on the right track, so I'll give you a little push. But first, I want to direct your attention to your keyboard. Look on the left side, above the caps lock key. There's a wide button with an arrow and the word "tab" on it. You should learn to use it when writing code.
Code:

```double integrate(double x1, double x2, int n) {         double sum=0, base=(x2-x1)/n;         for (int i=0; i<n; ++i)         {                 sum+=f(x1+i*base);         }         return sum*base; }```
Note that you might have written it like this:
Code:

```double integrate(double x1, double x2, int n) {         double sum=0, base=(x2-x1)/n;         for (; x1<x2; x1+=base)         {                 sum+=f(x1);         }         return sum*base; }```
However, I like the first better because due to rounding error, you might not get exactly n intervals with the second version. I also don't know why you chose "base" as the name for that variable. I'd have called it dx or delta_x or something like that.
• 04-10-2010
tabstop
Right now you're just printing f(0), f(1), f(2), etc. You need to call integrate 10 times to fill up your numbers array. Then you can sort that array using your favorite sorting technique.