Programming Exercise 5.25

You can approximate π by using the following summation:

Write a program that displays the estimated π value for i = 10000 through i = 100000 in steps of size 10000.

How to approach the problem

In the lecture on loops I showed an example of how to compute a similar sum:

The general form of a loop to compute a sum like this is

double term;
double sum = 0.0;
int n = 1;
while(n <= i) {
  term = ??
  sum = sum + term;
  n = n + 1;
}

You can also write this as a for loop:

double term;
double sum = 0.0;
for(int n = 1; n <= i; n = n + 1) {
  term = ??
  sum = sum + term;
}

In every different summation there will be a different relationship between the loop counter variable n and the nth term in the summation. To figure out what that relationship is you can look at a few example values for n and the term:

nterm
11
21/2
31/3
41/4

From these examples you can see that correct expression to compute the nth term is

term = 1.0/n;

(Note that I used 1.0 instead of 1 in the fraction. Since n is an integer variable the expression 1/n would use integer division and would evaluate to 0 for all n greater than 1. To avoid problems with integer division, we simply have to replace 1 with 1.0 in the division.)

For the sum you have to compute for this problem you will have to figure out what the relationship between n and the nth term is. Here is a table of the first few terms to help you see this relationship.

nterm
11
2-1/3
31/5
4-1/7

There are several different ways to generate the alternating plus and minus signs for the terms. I will leave it to you to find a way to do this.

Once you have written the loop that computes the sum you want, you are going to place that loop inside another loop that looks like this:

for(int i = 10000; i <= 100000; i = i + 10000) {
  // Loop to compute the sum goes here
  // Print the value of i and the sum here
}

If you want to use printf to print the results nicely lined up in two columns, you should use the %f format specifier to print the sum and the %d format specifier to print the integer i. You can read more about the printf method in section 4.6 of the textbook.