Reputation: 978
int main (int argc, const char * argv[]){
@autoreleasepool {
int x = 1;
for (x = 1; x <= 10; x++) {
NSLog(@"%i",x); //the answer here is 10.
}
NSLog(@"Number %i",x); //the answer here is 11.
}
return 0;
}
So my question is, why when I print 'x' outside the for loop it adds 1 to the initial 10?
thanks in advance.
Upvotes: 0
Views: 101
Reputation: 3324
The loop iterates for 10 times from 1 to 10 and when the loops ends the value of x becomes 11.
Upvotes: 0
Reputation: 187034
It because step clause x++
is run after the last successful loop iteration. That's how it knows to stop.
x = 1
, then we loop 10 times, incrementing it each time.x = 10
and your loop body runs its last time.x++
and now x = 11
x <= 10
, which is now false and the loop exits.If x
never got to 11, you would never know when to exit this loop.
Upvotes: 0
Reputation: 31579
Your loop is equal to
x = 1;
while(x <= 10)
{
// log x
x++;
}
As you can see, on the last iteration (x = 10) x is incremented and only then the loop breaks.
Upvotes: 2
Reputation: 101
Because "for" loop first increments the value of variable x and then compares with the condition!
Upvotes: 1
Reputation: 137342
It's not, the loop declaration adds it.
for (x = 1; x <= 10; x++) {
// some code
}
is like
x = 1;
while(x <= 10) {
// some code
x++;
}
When x = 11, the loop stops.
Upvotes: 2
Reputation: 16540
The loop ends once x is greater than 10. Therefore, it goes through the loop 10 times, adds one, which is 11 and breaks out of the loop.
Upvotes: 4