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>
usingnamespace std;
int main()
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
cout << sum << endl;
return 0;
}
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.
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