For Loop problem

Discussion in 'Mac Programming' started by pongster08, May 26, 2009.

  1. macrumors newbie

    Joined:
    May 26, 2009
    #1
    Hi im trying to make a for loop in Xcode
    Please look at code below, when i run it all i get is
    __________________________________

    [Session started at 2009-05-26 12:09:18 -0400.]
    9
    The Debugger has exited with status 0.
    ___________________________________




    #include <iostream>
    #include <cmath>
    using namespace std;

    int main()
    {
    int i;
    for (i=0; i<9; i++);
    {
    cout << i;
    }


    }

    ________________

    Thank you!
     
  2. macrumors newbie

    Joined:
    Jan 19, 2005
    Location:
    Washington, DC
    #2
    The output is correct. You are looping over nothing (";") until i is incremented to 9. Then you print out the value of i. You need to remove the semicolon before the block.
     
  3. thread starter macrumors newbie

    Joined:
    May 26, 2009
    #3
    Thank you!

    easy and clear ur response was. Thank you!
     
  4. macrumors member

    Joined:
    Jan 5, 2009
    Location:
    Switzerland
    #4
    Code:
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int main()
    {
    int i;
    for (i=0; i<9; i++)[COLOR="Red"][B];[/B][/COLOR]
    {
    	cout << i;
    }
    
    
    }
    
    Take away the semi-colon after the paranthesis at the end of the for line.

    Ben.
     
  5. macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #5
    Everyone makes this mistake when learning, so I thought I'd explain a little more as to what this is doing.

    A semicolon by itself basically means "do nothing." It is an empty statement. It is the same as curly braces with nothing inside them. {}

    So if you put a semicolon after the first line of a for loop (or a while loop, or an if statement, etc.), what you're really writing is
    Code:
    [b]for (i=0; i<9; i++)
    {
    }[/b]
    {
    	cout << i;
    }
    
    The code in bold is what the loop is actually doing. The cout has been "pushed out" of the for loop, and it will only execute once, after the entire loop is finished.
     

Share This Page