Program to Approximate Pi

I need help with my program that approximates pi. You are supposed to be able to enter n, or how many numbers are used in the series expansion to calculate pi. This is the formula: http://gyazo.com/1003158dede1593d491078454cd2394e.png

How do I use a loop to accomplish this?

Bump
Just apply the formula.

The question has been answered here:
http://www.cplusplus.com/forum/beginner/113332/#msg619209
impatient ...

You have not shown any code of yours yet. Make an effort to learn.


The sum equation is almost a loop. On every iteration you take a new i, place it into equation, evaluate, and add to running sum.
This may be a wee bit easier to understand:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main()
{
    int nterms = 1000000 ; // accept from user


    double sum = 0.0 ;
    int numerator = -1 ;
    const int upper_bound = nterms * 2 ;

    for( int n = 1 ; n < upper_bound ; n += 2 ) // for each term upto nterms
    {
        numerator *= -1 ; // alernating +1, -1, +1, -1 ...
        const double term = numerator / double(n) ; // +1/1.0, -1/3.0, +1/5.0 ...
        sum += term ; // +1/1.0 + -1/3.0, + 1/5.0 + -1/7.0 ...
    }

    const double pi = 4 * sum ; // 4 * ( 1/1.0 + -1/3.0, + 1/5.0 + -1/7.0 ... )

    std::cout << "pi upto " << nterms << " terms: " << pi << '\n' ;

}
@abhishekm71
Thanks, I'll look at the thread

@keskiverto
What are you talking about impatient? I don't have any code of my own, I just asked a simple question. Why would I be posting this thread if I wasn't making an effort to learn?

@JLBorges
Thank you very much.
Topic archived. No new replies allowed.