Do...While Loops
A do…while loop is similar to a while loop, but its condition is evaluated at the end of the loop instead of at the beginning. This means that a do…while loop will always execute at least once, but a while loop might not (because the condition might be false in the beginning).
Do…while syntax
Here is the syntax of a do…while loop:
do
{
//statements
} while (condition); //Notice the semi-colon!The very first thing that happens when we reach a do…while loop is that we execute the statements inside – even if the condition is initially false. At that point, we check the condition – if it is true, we loop back and repeat the statements. We continue this process until the condition becomes false.
Do…while example
Suppose we want to add up a list of numbers typed by the user until they type a 0. Here’s how we could approach the problem:
Scanner s = new Scanner(System.in);
//this declares several variables of the same type (int)
int num, sum;
sum = 0;
do
{
System.out.print("Enter an integer: ");
num = s.nextInt();
sum = sum + num;
} while (num != 0);
System.out.printf("The sum is %d%n", sum);This loop immediately asks for a number before checking any kind of condition. Note that the last number typed by the user (a 0, which ends the loop) IS added to the sum. However, this is OK because adding zero to a number does not change the number.