Rogier de Ruijter
Rogier de Ruijter

Reputation: 978

Why when I print a variable outside a for loop it adds 1 to it?

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

Answers (6)

Abdullah Md. Zubair
Abdullah Md. Zubair

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

Alex Wayne
Alex Wayne

Reputation: 187034

It because step clause x++ is run after the last successful loop iteration. That's how it knows to stop.

  1. x = 1, then we loop 10 times, incrementing it each time.
  2. You get to x = 10 and your loop body runs its last time.
  3. The step clause then runs x++ and now x = 11
  4. Check loop condition 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

Daniel
Daniel

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

Joss01
Joss01

Reputation: 101

Because "for" loop first increments the value of variable x and then compares with the condition!

Upvotes: 1

MByD
MByD

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

MarkPowell
MarkPowell

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

Related Questions