The only way that the loop could be exited in normal circumstances, is if num
became 0
. But you never reassign num
to any other number, so it is always 31
, so the loop won't end (in a regular manner).
What happens though is in your loop you're incrementing j
on every pass. j
is declared an int. int
s have maximum values defined, after which they go to minimum value, so from maximum (positive) number, after another increase you get a minimum (negative) number. Then you count up till you reach 0
. And then the exception is thrown as the application tries to divide by 0
.
(see here: What happens when you increment an integer beyond its max value?)
The reason you see 400000
as the first displayed value is because the loops go so fast, that the console is not able to handle it gracefully, and you see just some of the outputs displayed.
Not sure what you're trying to achieve, but in order for this program to work differently, either change the loop condition or add a break
statement inside - as mentioned in the comments.