Help with Summation Loop

I'm trying to figure this loop out but the output isn't showing because I keep making an infinite loop I think. Can anyone help me fix this?

Radius and error(not error_2) are user inputs. If the absolute value of the calculated error(error_2) is less than or equal to error, then area is considered the area. If not, loop to the width equation and increase n by 1.

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
  double radius, error, error_2, area, area_2, width;
  int count;
  area = 0;
  area_2 = 0;
  error_2 = 0;
  
  cout << "Enter Radius: ";
  cin >> radius;
  cout << "Enter Error: ";
  cin >> error;

  n = 1;
  count = 0;
  width = 0;
  
  do
  {
     count++;
     width = radius / n;
     for (int i = 1; i <= n; i++)
     {
	area += width*(sqrt(pow(radius, 2.0) - pow((width*(i - 0.5)), 2.0)));
     }
     area_2 = 4 * area;
     error_2 = abs(area_2 - M_PI*pow(radius, 2));
     n++;
     } while (abs(error_2) > error);
				
     cout << "Computer Area: " << area_2 << "	Error: " << error_2 << "	Number of Iterations: " << count << endl;
What exactly is this code supposed to do? A better understanding of your code could help us to come up with solutions / alternatives.
It's supposed to find the area of a circle using rectangles. Its supposed to do these steps:

Initialize a variable called n to 1

Compute width of the rectangles as w=r / n

Compute the area by adding up the areas of all rectangles, as
area=4 x SIGMA(n on top and i=1 on bottom)〖w×√(r^2-(w×(i-1/2))^2 )〗

Compute the error
error=|area-π∙r^2 |

If the absolute value of error is less than or equal to the acceptable error entered by user then consider the current area value as close enough to be the real area of the circle. Otherwise, increase n by 1 and then loop to step 2.

Display the computed area, the absolute value of error, and the number of iterations it took to reach the solution.
You forgot to reset the area inside the loop.
I added it inside the loop but I'm getting zeros for all my outputs now.
It seemed to work for me. Are you sure you put it in the right place?
Last edited on
Yeah I'm pretty sure. The whole code is one giant choice statement. Should I post that so you can view it?
Topic archived. No new replies allowed.