Search code examples
javafor-loopwhile-loopinfinite-loop

Why is while loop inside a for loop entering into an infinite loop?


While loop entering into infinite loop.

    for(int s=1; s<=500; s++)
    {  
        //System.out.println(i);
        int total=0;
        while(s != 0) {
            //System.out.println(s);
            int digit = s % 10;
            //System.out.println(digit+" "+s);
            total = total+(digit*digit*digit);
            //System.out.println(total);
            //reversed = reversed*10 + digit;
            s = s/10;
            //System.out.println(s);
            }
        if (total==s) {
            System.out.println(s);
        }
    }
    

When i try to run this it enters into an infinite loop, if anyone can explain it and then the last if never gets executed. I am trying to print armstrong numbers from 1 to 500. If anyone can debug it and give me the correct code or at least help me get to know what is going on here.


Solution

  • I believe while loop will not be infinite because s/10 will return 0 (keep in mind it's all integer and in integer 1/10 = 0).

    The for loop however will be infinite because each time you run through the while loop you set s to 0 and then the instruction in the for loop increments it by 1, so s ends up being 1 in every iteration of the for loop.

    As for the if statement, it does not execute because in your code total = total+(digit*digit*digit); where digit = s % 10 that results to 1, hence in the if condition you'll end up with a condition 1 == 0 that will always evaluate to false