1

How do I calculate the sum to below in C++? I tried the following code but failed.

enter image description here

#include <iostream>
using namespace std;
int main()
{
    int n, p, r = -1;
    cin >> n;
    for (p = 0; p < 10; p++)
        r *= (-1);
    cout << r << endl;
    return 0;
}
6
  • That's basic maths, it's 1*(10+1). Commented Jan 26, 2012 at 16:45
  • Why are you inputting n? Your expression says that n starts from 0 and goes to 10. Commented Jan 26, 2012 at 16:47
  • 1
    I suspect the sum should read sum( n=0, 10, (-1)^(n+1) ), so the result is either -1 or 0 Commented Jan 26, 2012 at 16:48
  • 2
    that's still basic maths, no need for a loop, you just -1 * upperLimit%2 Commented Jan 26, 2012 at 16:51
  • Look at the series and think: -1 + 1 -1 +1 -1 +1 ... Commented Jan 26, 2012 at 16:51

3 Answers 3

4
#include <iostream>
using namespace std;
int main()
{
    int p, r = 1;
    int iSum=0;
    // cin >> n;

    for (p = 0; p <= 10; p++)
    {
        r *= (-1);
        iSum+=r;
    }
    cout << iSum << endl;
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

4

That's basic mathematics, there is no need for a loop, you can just calculate -1 * (upperLimit + 1)%2.

Look at the series and think: -1 +1 -1 +1 -1 +1 ....

3 Comments

+1 yes, in general it would be x * upperLimit % 2. Great answer!
@MRM, that would produce a positive 1 or a 0, depending on the upderLimit. The only possible sums are -1 or 0. 10 % 2 = 0, 0 * -1 = 0. 11 % 2 = 1, 1 * -1 = -1. I think this is in an old Calculus book of mine as a telescoping series. I'll verify.
While accurate, this doesn't apply to more complex examples.
1

Although @Flavius is right, the sum starts from 0 so it'll be -1 * (upperLimit+1)%2 as the sum iterates not 10 but 11 times. The upperLimit%2 thing works for sums starting at 1

P.S: Sorry for answering, I cannot yet comment, just registered.

1 Comment

Thanks, I was aware of that but I was too lazy to fix it. +1 and welcome on SO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.