4️⃣

# 8.4 Do-While Loops

Ch. 8 Loops

There is a variation of a while loop called a do-while loop. The only difference between the two is that the code inside of a do-while loop always runs at least once. This is the general format:
``````do {
// do stuff
} while (condition);``````
Notice that the condition is put at the end of the curly braces and that there is a semicolon at the end, unlike at the end of a for loop or while loop.

Here’s an example of how a do-while loop can be used:
``````import java.util.Scanner;

final int SECRET_NUMBER = 12;

System.out.println("Welcome to the guessing game!");
System.out.println("Guess the correct positive integer or -1 to quit.");

Scanner input = new Scanner(System.in);

int guess;
do {
// prompt user for their guess
guess = input.nextInt();
} while (guess != SECRET_NUMBER && guess != -1);

if (guess == SECRET_NUMBER) { // user guessed correctly
System.out.println("Good job, you guessed right!");
} else { // user quit
System.out.println("The secret number was " + SECRET_NUMBER);
}``````

Sample output 1:
``````Welcome to the guessing game!
Guess the correct positve integer or -1 to quit.
The secret number was 12``````

Sample output 2:
``````Welcome to the guessing game!
Guess the correct positve integer or -1 to quit.
Good job, you guessed right!``````

The program above is a simple guessing game. It prompts the user to enter guesses for a secret number (which is 12). It keeps asking the user to guess while their guess is incorrect and not equal to -1. (-1 is the sentinel value which the user uses to tell the program that they want to stop.)
Notice that I have to declare `guess` to be outside of the do-while block. If I declared it inside of the block, I would not be able to access the variable in the condition of the loop because the variable’s scope would only be within those curly braces.

3️⃣
8.3 While Loops

## Next Section

5️⃣
8.5 Break and Continue

⚖️