Volatile
Volatile

Reputation: 677

Different for-loop incremental value

I recently fiddled around with some for loops, and tried to get my head around some of the logical part of it. While i'm far beyond the level of loops at this point, I still tend to get a bit weird when it comes to logic sometimes.

However, I found that the incremental value of a for loop is different depending on whether you are inside or outside the loop:

int i;
for(i = 0; i < 10; i++) {
   System.out.println(i); // 0 ... 9
}

System.out.println(i); // 10

Now, i'm afraid one day i'll come to a point where i'll have to use the counter for something more than just matching it against the condition...

Now I think I understand why this is happening; i is being incremented after the condition fails and the loop dies, but is that really supposed to happen?

Is there any mathematical/logical (or elegant) way to not make it go N+1 after loop termination, that i'm missing here?

Upvotes: 1

Views: 156

Answers (2)

Denzil
Denzil

Reputation: 326

Since the increment occurs after the checking, in the loop:

for(int i = 0; i < 10; i++)

once 9 < 10, i increments and 9 is printed whereas i has 10 now.

Therefore, System.out.println(i); gives 10 as the answer.

Upvotes: 0

zw324
zw324

Reputation: 27210

That is how a for loop works:

  1. check the condition, if it holds go to 2, else terminate;
  2. run body;
  3. execute the modification, go to 1.

So in a word, you cannot.

Also, how could the loop terminate if the variable does not go to N + 1? In the case, the loop condition always holds, so it will run forever.

Upvotes: 4

Related Questions