Theresa
Theresa

Reputation: 19

How to add two sums, loop and add the first sum with with another?

I'm trying find out how to add sum while doing a for loop, if that makes any sense? Like for instance:

 float a = 0;
 int main(){
    float sum = 0;

    for(int n = 1; n < 100; n++){ //n increases everytime
        sum = (1.0/(n * (n+1.0)));
        a = sum;
        cout << a << endl;
    }

How would I take the value of 'a' when n = 1, then add it to the value of 'a' when n = 2, then continuously do that? Then take the sum of the two "a's" and add it to when n = 3? Sorry if it's a bit confusing because I don't really get it myself... if it helps, here's an example:

(1/(1*2)) + (1/(2*3))+ (1/(3*4))+...(1/(n*(n+1)))

Upvotes: 0

Views: 82

Answers (1)

M.Fooladgar
M.Fooladgar

Reputation: 384

It seems you need this code:

float a = 0;
for(int n = 1; n < 100; n++){ //n increases everytime
  sum = (1.0/(n * (n+1.0)));
  a += sum;
}
cout << a << endl;

Upvotes: 4

Related Questions