I can't understand why doesn't this loop in Java terminate.
long i = 26L ;
long j = 24L ;
for (long x = 0L ; x < 1000L ; x++) {
i = i / 12 + 23 * (--x ) ;
j = (x--) + j + 5 ;
}
In each iteration of the loop, you are decrementing the counter x
twice. This means practically that the upper bound of the loop will never be hit. In fact, the counter should go negative even after the first iteration.
This is what you probably intended to do:
for (long x = 0L ; x < 1000L ; x++) {
long xTemp = x;
i = i / 12 + 23 * (--xTemp ) ;
j = (--xTemp) + j + 5 ;
}
or possibly this:
for (long x = 0L ; x < 1000L ; x++) {
i = i / 12 + 23 * (x-1L) ;
j = (x-1L) + j + 5 ;
}
In general, if you designate x
as for
loop counter, then you should not be messing around with it inside the loop as a matter of good practice. You can use its value inside the loop, but let the loop itself manage it.