How would I write a program which takes an integer n and produces the output of the sum of the alternating series. So if I were to enter 5 it would say 3 because 1 - 2 + 3 - 4 + 5 = 3.

I'm not sure where to start

Thanks.

Printable View

- 05-30-2013, 04:10 PMlchSimple question: Alternating sum
How would I write a program which takes an integer n and produces the output of the sum of the alternating series. So if I were to enter 5 it would say 3 because 1 - 2 + 3 - 4 + 5 = 3.

I'm not sure where to start

Thanks. - 05-30-2013, 04:15 PMKevinWorkmanRe: Simple question: Alternating sum
How do you do it without a computer, with a pencil and a piece of paper? Work through a few examples until you see a pattern.

Pretend you have a really dumb friend who has no idea how to do this. Write instructions (in plain language, not code) that your friend could follow to achieve the task. Remember how dumb he is, so make the instructions really short and really simple. When you have that written out, you'll have an algorithm that you can start thinking about implementing. - 05-30-2013, 04:19 PMjim829Re: Simple question: Alternating sum
Well, first you need to know how to sum up a series of integers. Then, once you have that, you need to think about how to alternate the sign of every other one, starting with the second.

Regards,

Jim - 05-30-2013, 04:41 PMJosAHRe: Simple question: Alternating sum
You can also think a bit before you start writing loops and sums ... look at your series: (1-2)+(3-4)+(5-6)+(7-8) ... == -1 + -1 + -1 + -1 ... if the largest number is even, the result is -n/2, otherwise the result is -n/2+n. We don't need no steenkin' loops ;-)

kind regards,

Jos - 05-30-2013, 04:50 PMjim829Re: Simple question: Alternating sum
- 05-30-2013, 05:38 PMJosAHRe: Simple question: Alternating sum