The Student Room Group

alternatingSum(n)

Hello guys. Can you help me out with this question? By the way, I am still new in c++ programming and try to enhancing my knowledge in c++ language.
So, the question is, to write a function named alternatingSum(n) that computes and returns the sum of the numbers 1 through some integer n where the sign alternate between + and -. For example, when user input a value of 7, so the function be like alternatingSum(7) should return 4 because 1 2 + 3 4 + 5 6 + 7 = 4.

Thank you in advance for your help!
Reply 1
I don't know C++, but the idea is to iterate through all the numbers up to n, and check if the number is even. If it is, you subtract it from the running total, and if not, you add it. Do you know how to check if a number is even?

Quick Reply

Latest

Trending

Trending