Other Loop Information

This section contains additional information for working with loops.

Infinite loops

It is very important that we do something inside the body of the loop that will eventually make the condition false. Otherwise, the loop will execute forever – we call this an infinite loop. For example, consider the loop below, which is supposed to print the sum of the numbers between 1 and 4:

int sum = 0;
int count = 1;
//warning: this is an infinite loop!
while (count < 5) 
{
    sum = sum + count;
}
System.out.printf("Sum: %d%n", sum);

This loop will never finish executing. We told the loop to keep going while count < 5 – but we NEVER change count inside the loop. Thus count is always 1, and the loop never ends. You can usually tell you have an infinite loop if your program just hangs without completing the execution.

Here is the corrected version of the loop:

int sum = 0;
int count = 1;
while (count < 5) 
{
    sum = sum + count;
    //update count so the condition will eventually be false
    count = count + 1;
}
System.out.printf("Sum: %d%n", sum);

Break statements

Recall that a break statement can be used to leave a switch case statement without evaluating any of the other cases. We can also use a break statement in a loop, which will let us immediately exit the loop without finishing the current iteration or checking the loop condition. For example, suppose we want to add up 10 numbers that the user types – unless the user types a 0, in which case we want to immediately stop and report the sum up to that point. Here’s how:

Scanner s = new Scanner(System.in);

int sum = 0;
int count = 0;

while (count < 10) 
{
    System.out.print("Enter a number: ");
    int num = s.nextInt();
    sum += num;

    //Exit loop if num was 0
    if (num == 0) break;
    count++;
}

System.out.printf("Sum: %d%n", sum);

When we run this program, it will ask for numbers either until it has asked 10 times (and the loop ends), or until the user types a 0 (in which case we immediately leave the loop). It then prints the sum.

Continue statements

The continue statement allows us to skip the rest of the code for the current iteration and instead immediately start on the next iteration. For example, suppose we again want to add up 10 numbers that the user types – but if they enter a negative number, we don’t want to add it to our sum. Here’s how:

Scanner s = new Scanner(System.in);

int sum = 0;
int count = 0;

while (count < 10) 
{
    System.out.print("Enter a number: ");
    int num = s.nextInt();

    //Ask for next number if a negative number was entered
    if (num < 0) continue;
    
    sum += num;
    count++;
}

System.out.printf("Sum: %d%n", sum);

This will ask for 10 numbers from the user. If a number is negative, we skip the rest of the loop (the part where we add num to our sum) and start on the next iteration (where we ask for another input number).