Increments in for loops in C++

Discussion in 'Mac Programming' started by sheepopo39, Dec 10, 2009.

  1. sheepopo39 macrumors 6502

    Joined:
    Sep 18, 2008
    #1
    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?
     
  2. kpua macrumors 6502

    Joined:
    Jul 25, 2006
    #2
    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.
     
  3. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #3
    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
    }
    
     
  4. chrono1081 macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar
    #4
    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.
     

Share This Page