Regis Santos
Regis Santos

Reputation: 3749

Calculating the sum in C++

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;
}

Upvotes: 1

Views: 332

Answers (3)

Flavius
Flavius

Reputation: 13816

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 ....

Upvotes: 4

prajmus
prajmus

Reputation: 3271

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.

Upvotes: 1

MRM
MRM

Reputation: 435

#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;
}

Upvotes: 4

Related Questions