Confused "for" Help!

I don't get how the output would be "Sum is 2550". Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
 int sum = 0;

 for ( int number = 2; number <=100;number += 2)
 sum += number;

cout << "Sum is " << sum << endl;

return 0;
}
Last edited on
You're running the wrong program? It should only display:
1
2
3
4
5
6
7
8
9
10


Edit: Or this isn't your entire code.
Last edited on
OH, crap. My bad Volatile LOL. I was trying out each examples on the book.
Last edited on
There's its fixed.
Do you know how a for loop works? If so, it shouldn't be too hard to figure out. Go re-read the section of your book on them then ask here if there is something you don't understand about the explanation.
As a general suggestion when debugging, if often helps to simplify the problem. If you don't understand why it's not giving you the result you expect, try a simple case, like

1
2
3
 
for ( int number = 2; number <=10;number += 2)
sum += number;


this is much easier to do in your head or on paper, and you can more quickly see why results don't match your expectations.
Topic archived. No new replies allowed.