Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

sheepopo39

macrumors 6502
Original poster
Sep 18, 2008
251
0
I was reading through my book on C++ and I reached for loops.

Code:
for (i = 1; i < 10; i++)
{
cout << i << endl ;
}

The book told me that on each iteration of the loop, the variable is incremented, then the statement is executed. However, if it's like this, shouldn't it output one extra number because it wouldn't be evaluated until after the iteration. (Like instead of the output ending at 9, it ends at 10) I don't get it, can anyone try to help me make sense of this?
 
The order of execution is this:

Code:
1. ENTER FOR LOOP
2. Initialization (i = 1)
3. Check condition (i < 10)
    if false, go to 7.
4. Perform block (cout << i << endl;)
5. Increment (i++)
6. Go to 3
7. EXIT FOR LOOP

So when i is incremented from 9 to 10, the condition is checked again and evaluates to false, so step 4 is skipped.
 
Your for-loop laid out as a 'while' statement

Code:
i = 1;                  // initialization
while (i < 10)          // test condition in order to execute
{
    cout << i << endl;

    i++;                // bottom of-loop execution statement
}
 
i is less then 10 not equal to 10.

To clarify:

The loop: for(i = 1; i < 10; i++) reads like:

for i equals 1. while i is less then 10, increment i by 1 each time through the loop.

The first iteration occurs and increments i by 1 and so on.

Whatever you set i equal to will be its initial value through the first loop then it will increment until it reaches 10. It wont print 10 because the condition states that i must be less then 10 for the loop to continue.


Youll get the hang of all of it and later wonder why on earth you ever got tripped up on for loops. Its the nature of learning to program.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.