Sum of 1-1/2+1/3-1/4...

Hello. I'm new to C++ programming and I'm struggling with quite a hard (at least to me) task. I have to make a program that sums Sn=1-1/2+1/3-1/4+...+1/9999-1/10000 in different cases:

a) Sum it from left to right.
b) Sum it from right to left.
c) Sum it from left to right, but positive and negative numbers separately.
d) Sum it from right to left, but positive and negative numbers separately.

Last edited on
Algorithm in itself is really easy. The only thing you need is to remember few things:

1. You want a variable S to hold the total. Store result in a double, not int, because it's a real number (with decimal part).

2. Do it in a for loop with counter starting at int i = 1 and loop condition being i <= n (10000?); (http://www.cplusplus.com/doc/tutorial/control/#for)

3. Use if (i % 2) to detect odd numbers and else for even

4. In each loop iteration either add or subtract 1.0 / n (1.0 not 1 - because you want the result to also be a double, not int)

5. The difference between a and b is wheter you loop from 1 to n up or from n to 1 down

6. c and d only require the loop to increment +2, not +1 per iteration, and start from 1 or 2 respectively
Last edited on
Topic archived. No new replies allowed.