infinite loop printing a negative number without looping forever

Viewed 41
    public static void main(String[] args) {
        int sum = 0;
        int count = 5;
        while (count >1){
            sum = sum + count;
            count = count + 1;
            
        }
       System.out.println(sum); 
    }
}

its printing either negative number or -4 , I want to run a infinite loop code which executes

2 Answers

If the program does run for infinity, you'll never get an answer :-)

Integers in Java are signed and when they do overflow above the maximulm, they will flip to negative numbers and hence terminate the loop.

You can use a while(true) for an infinite loop.

  1. Firstly, "count" mentioned as int data type (range is -2^31 to 2^31 -1) , so "count" is incremented until it reached maximum value (which is positive range), after that count will point to minimum (value which is negative range).

In simpler words, it works in round robin fashion, i.e., after completing the max value, it starts from min value again

  1. Below are some of the ways used for infinite loops.

a. While loop

Example :

while (true) 
            {
            } // As boolean is set to true, loop runs infinite times

b. For loop

Example :

for (;;) 
           {
           } // As there is no condition passed in for, it iterates infinite times

c. Do while loop

Example :

do { 
             } while (true);
    // As while condition clause is set to true, so loop runs infinite times

Note: When applications exit/ when memory overflow error occurs, code will come out of infinite loops

Related