Answer only comes out to be 0 from a while loop?

Hi, I am pretty new to C++ and I am wondering what is wrong with this code--
I am basically doing a reimanm sum with trapezoids. I think I have the idea down, but my answer always comes out to be zero. Have I made a mistake with the while loop? Should I not have set the area = to zero initially? This is for a homework assignment.

You enter two initial x values, then the y values for those x values are found from an equation (in the code). I'm calculating the area under the curve from xa to xb with step sizes of s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 #include <iostream>
#include <cmath>

using namespace std;

int main ()
{

double xa; //x1
double xb; //x2
double ya; //y1
double yb; //y2
double e = 2.71828182845904523536;
double s;
double xc; //temporary x value
double area=0;
double a; //temporary area
cout << "Enter x0" << endl;
cin >> xa;
cout << "Enter x1" << endl;
cin >> xb;
cout << "Enter step size" << endl;
cin >> s;

while (xc > xb)
{
	xc = xa + s;
	ya= xa * pow(e, xa) * sin(xa);
	yb = xc * pow(e, xc) * sin(xc);
	a = (xc - xa) * ((ya + yb)/2);
	area = area + a;
	xa = xc;

if (xc == xb)
{
	break;
}

}

cout << "Area estimate: " << area << endl;


return 0;

}
Last edited on
xc is not initalized to any particular value, so I suspect the condition on line 25 is false when it is encountered the first time so the body of the loop is never executed.
Also why is there a break if xc that's not defined or a calculated value before the while loop, in the while loop?

Would it be better to do do-while loop?

I hope that helps,

~ Hirokachi
Thank you- that helped me find my mistake (after almost an hour of frustrated looking haha). I should have set xc=0 initially, and xc should have been less than xb in the while loop- not greater than. Oh well, at least I'll remember to be more careful next time.
Topic archived. No new replies allowed.