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

pongster08

macrumors newbie
Original poster
May 26, 2009
8
0
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!
 

mesa

macrumors newbie
Jan 19, 2005
19
0
Washington, DC
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.
 

HyperSnake

macrumors member
Jan 5, 2009
74
0
Switzerland
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.
 

autorelease

macrumors regular
Oct 13, 2008
144
0
Achewood, CA
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.