-9

Here when I add System.out.println(j) inside the loop, the initial number is random, and the next outputs are huge values from 400000 Value of j is Initialized to 1, does while loop counts all int values unless mentioned?

public static void main(String[] args) {
    int num = 31;
    int j = 1, c = 0;
    while (num != 0) {
        //System.out.println(j);
        if (num % j == 0) {
            c += j;
        }
        j++;
    }
    System.out.println(c);
}
Abra
  • 19,142
  • 7
  • 29
  • 41
Ae Ri
  • 185
  • 1
  • 12
  • 2
    Java is to Javascript as Pain is to Painting, or Ham is to Hamster. They are completely different. It is highly recommended that aspiring coders try to learn the name of the language they're attempting to write code in. When you post a question, please tag it appropriately - this lets those with knowledge of the language you need help with to see your question. – CertainPerformance Oct 04 '20 at 17:48
  • 1
    The value of `num` never changes, so the program will run forever. – Pointy Oct 04 '20 at 17:49
  • 2
    @Pointy Not forever. When `j` reaches 0, it will error. – khelwood Oct 04 '20 at 17:54
  • 1
    A while loop continues until the loop-condition becomes false, or the loop is ended prematurely because of a break-statement. – NomadMaker Oct 04 '20 at 18:54

1 Answers1

1

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. ints 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.

Michał Schielmann
  • 1,372
  • 8
  • 17