Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this infinite Loop converge?

Tags:

java

math

Why does this code in Java output the value -210, when it's an infinite Loop?

Does this loop end when the integer reaches its max value?

public static void main(String[] args)
{
    int a=100;
    int b=110;
    int c=0;
    while(a>=100 && b<=110) {
        a=a+1;
        b=b-1;
        c=a-b;
    }
    System.out.println(c);
}
like image 564
Vilches Felipe Avatar asked Mar 14 '26 03:03

Vilches Felipe


2 Answers

This loop terminates due to integer overflow. When a reaches the max value of int, incrementing it makes it negative. When b reaches the min value of int, decrementing it makes it a large positive. Once one of them overflows, the loop terminates.

Due to the initial values, a would overflow first, since both are initialized to positive values, so a is closer to Integer.MAX_VALUE than b is to Integer.MIN_VALUE.

As to why the output it -210 :

a is incremented (Integer.MAX_VALUE-100)+1 times until the loop terminates
b is decremented the same number of times.

The final a is Integer.MIN_VALUE (due to overflow)
The final b is 110 - ((Integer.MAX_VALUE-100)+1) = 110 - ((-Integer.MIN_VALUE-1-100)+1) = Integer.MIN_VALUE + 210

Hence, a-b ends up being Integer.MIN_VALUE - (Integer.MIN_VALUE + 210) = -210

like image 101
Eran Avatar answered Mar 16 '26 18:03

Eran


Let me add to Eran's answer.

The variable a will wrap around when it reaches INT_MAX, and so does b when it reaches the negative of INT_MAX.

Which one reaches the limit first? a will.

Then the condition on a>=100 will fail, so the loop will finish.

At the time the loop finishes, the value of b will be 110 - (INT_MAX - 100).

Thus, c = a - b = -INT_MAX - ( 110 - (INT_MAX - 100) ) = 210;

like image 22
Taesung Park Avatar answered Mar 16 '26 18:03

Taesung Park



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!