Advertisement

Stupid Question

Started by May 03, 2000 06:08 PM
4 comments, last by Nazrix 24 years, 7 months ago
I'm a little embarrassed to ask such a basic question but I want to make sure I'm thinking correctly. if I have a for loop like this: for (a=1; a<=10; a++) { } will a be 1 the first iteration or will it be 2 because of the a++ ? also, when a reaches 10 will it be 11 for the last iteration because of the a++ ? thanks Edited by - Nazrix on 5/3/00 6:09:51 PM
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
That is not a stupid question.

First time through the loop, a will equal 1. Last time through the loop, a will equal 10. a will equal 11 below the loop, but will not go through the loop as 11.

aig
aig
Advertisement
Here''s how it breaks down:

for (how to initialize the variables;
do this loop only if this is true;
AFTER the loop is executed, do this) {

blah blah

}

So it''s legal to have loops like:
for (bool found=false, int x=0; !found, x<10; x++) {
if (x==4) found=true; // stupid, but makes a point
}

Get what that loop does?
I think I do get what that loop does...interesting...

ok that helps a lot...thanks



Edited by - Nazrix on 5/3/00 7:05:13 PM
Need help? Well, go FAQ yourself. "Just don't look at the hole." -- Unspoken_Magi
Nazrix,

The best way to check out what the loop does is to put a debug/output statement inside the loop, like so:

for(a=1;a<10;a++)
{
cout << a << endl;
}

That way you can actually see what happens to a when the program runs. This is a very useful way to figure out code in a lot of situations. PLUS, learn to use your compiler''s debugger, also VERY useful.

Req
dddDDDdddDDDdddDDDdddDDDddd Big Brother is Watching

for (a=1; a<=10; a++)
{
}
<\quote>

your if statement is equivalent to this:

a = 1;
while(a <=10)
{
//whatever you had inside your brackets
a++;
}
even to the point that you can expect a to be 11 when that cycle is exited (but only ten in the last run , as An Irritable Gent said).

Edited by - alexmoura on 5/6/00 5:57:06 AM

This topic is closed to new replies.

Advertisement