ballenavoladora
ballenavoladora

Reputation: 67

Why doesn't this Java loop terminate?

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 ;
}

Upvotes: 0

Views: 80

Answers (3)

I can't understand why doesn't this loop in Java terminate.

well, the variable x starts with zero, and on every iteration its value will increase by 1 (by doing x++) but decreased twice (by doing --x) the arithmetic will be at the end that x decreased 1 after every iteration,

Technically speaking x will be some when negative and then UNDERFLOWS, at that point in the underflow x will be bigger than zero again and then this condition will be true: x < 1000L

for (long x = 0L ; x < 1000L ; x++) {
    i = i / 12 + 23 * (--x ) ;
    j = (x--) + j + 5 ;
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

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.

Upvotes: 5

Keith John Hutchison
Keith John Hutchison

Reputation: 5277

The key is what x-- does ... and what x++ does. x will never reach 1000L.

Upvotes: 0

Related Questions