PDA

View Full Version : For Loop problem




pongster08
May 26, 2009, 11:09 AM
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
May 26, 2009, 11:14 AM
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.

pongster08
May 26, 2009, 11:17 AM
easy and clear ur response was. Thank you!

HyperSnake
May 26, 2009, 01:46 PM
#include <iostream>
#include <cmath>
using namespace std;

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


}


Take away the semi-colon after the paranthesis at the end of the for line.

Ben.

autorelease
May 26, 2009, 02:54 PM
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
for (i=0; i<9; i++)
{
}
{
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.