Help with "For"

I am very green to programming. Just started learning today. I am confused why in this code that integer 'sum' doesnt equal 100. I keep getting 0. Thank you in advance!

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
cout << sum << endl;
return 0;
}
You do realize you for loop goes from -100 to +100, right?

The positive numbers and negative numbers are going to cancel each other out resulting in a sum of 0.
closed account (SECMoG1T)
You got 0 because it is the correct answer according to your loop range
The way i misunderstood it was that integer "i" would just go -99, -98, etc,. All the way up to 100. Then later in the code integer "i" would be assigned to sum. Which would be 100. Im confused here.
If someone doesn't mind I would appreciate a correction on my thinking error. I'm obviously missing something here.
i starts at -100 and ends at +100.

First time through the loop, i = -100. Last time through the loop, i = +100.
-100 + 100 = 0.
-99 + 99 = 0.
etc.


But why would the positive integer go down by one every time? The way i understand it only the -100 should go down by 1 because of the ++i
@clypso

1
2
3
4
5
6
7
8
for (int i = -100; i <= 100; ++i)
sum += i;
// First sum = -100;
//Next sum = -199;
//Next sum = -297;
//Sum goes more negative with each -i
// Then i goes up the value of each plus i
// Till sum equals 0 
But why would the positive integer go down by one every time?

What are you talking about? i starts at -100 and goes UP by one each time through the loop.
Oh.. Ok. Thank you everyone for your support! Much appreciated. I see where I went wrong.
Topic archived. No new replies allowed.