Here is the code –
int i = 0;
System.out.printf( "\n%d\n\n", i ); // show variable i before loop
for( i = 0; i < 8; i++ )
{
System.out.printf( "%d\t", i );
}
System.out.printf( "\n\n%d\n", i ); // show variable i after loop
Here is the output –
0
0 1 2 3 4 5 6 7
8
My problem arises when I want to use the variable i after the exit of the for loop. I would assume that i is reading 7, the 8th increment in zero based counting but it actually reads as 8!!! One more increment to variable i has been made on loop exit.
In order to remedy this I would have to do something like i– at the end of the loop and before using it in any further code. This seems to me to make the code harder to understand.
Is there a better solution?
When
iis 7, the conditioni < 8is still fulfilled, so there is no reason to exit the loop.It is not very clear to declare the loop variable before the loop and use it afterwards anyway. Rather, consider declaring the loop variable with the loop statement.
If using
numIterations-1really bothers you, you could also instead useint maxCounter = 7and usei <= maxCounterinstead as loop invariant.