While Loops

The simplest kind of loop is a while loop*. This loop executes a set of instructions repeatedly until a given condition becomes false.

While loop syntax

Here is the syntax of a while loop:

while (condition)
{
    //statements
}

Here, condition is evaluated before anything inside the loop is executed. If the condition is false, we immediately skip to the code after the loop. If the condition is true, we execute the statements inside the loop, and then check the condition again. If the condition is false, we leave the loop. If it is still true, we execute the loop again. We repeat this process until the condition becomes false.

While loop example

Here is how we can use a while loop to print the sum of 100 numbers entered by the user:

Scanner s = new Scanner(System.in);

//keep track of the sum of the elements we’ve seen so far
int sum = 0;
//keep track of how many elements we’ve asked for
int count = 0;

//keep looping while we haven’t asked for 100 elements
while (count < 100) 
{
    //ask for the next number
    System.out.print("Enter a number: ");
    int num = s.nextInt();

    //add the number to the sum we have so far
    sum = sum + num;

    //add one to our count (we’ve asked for one more number)
    count = count + 1;
}

//the loop is over – sum now holds the sum of 100 values
//print the sum
System.out.printf("The sum is: %d%n", sum);

Combining loops and conditional statements

We can also put conditional statements inside of loops (or loops inside of conditional statements). In this example, we want to print the sum of 100 positive numbers. If the user enters a negative number, we want to print an error and not add the number to our total:

Scanner s = new Scanner(System.in);

int sum = 0;
int count = 0;

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

    //only add the number if it is positive
    if (num > 0) 
    {
        sum = sum + num;
        count = count + 1;
    }
    //otherwise, print an error
    else 
    {
        System.out.printf("Error: %d is not positive%n", );
    }
}

//the loop is over – sum now holds the sum of 100 values
//print the sum
System.out.printf("The sum is: %d%n", sum);