Actually, your code does not go into an infinite loop. The other answers already told you why your code doesn't end in the time you've expected it to end (since you increment num
in the inner loop, thus rendering i < num
less useful than expected), but let me show you that your loop still is able to finish.
I have changed your code a bit:
int num = new Scanner(System.in).nextInt();
int i;
for (i = 0; i < num; i++) {
for (int j =0; j <=i; j ++) {
num = num +1;
}
}
System.out.println("final i: " + i);
System.out.println("final num: " + num);
As you can see I moved the declaration of the i
out of the for
block in order to be able to access it later and I removed the System.out.println
calls inside the loop, because they are time consuming (Java synchronizes the access to the console resource). This program now doesn't even take that long to finish, just one or two seconds (depending on your system performance).
The result for the input "500" looks like this:
final i: 65536
final num: -2147450380
As you can see, the program finished and i
has the value 65536 (it has that for any number you enter for the initial value of num
) and num
is negative. This happens, because int
has a value range from -2,147,483,648 to 2,147,483,647 and when you increment a number over the maximum, it "overflows" (if you decrease a number under the minimum value, it "underflows"). The code increments num
inside the inner loop, thus more often than i
in the outer loop. That means that num
reaches the maximum value for integer earlier than i
and overflows earlier. In that moment i < num
becomes true
and the outer loop will be exited.