Java > Core Java > Control Flow > Do-While Loop
Do-While Loop Example: Number Guessing Game
This example demonstrates the use of a do-while loop in a simple number guessing game. The program will repeatedly ask the user to guess a number until they guess correctly. The do-while loop guarantees that the user will be prompted at least once, even if they guess correctly on the first try.
Code Snippet
This Java code implements a number guessing game using a do-while loop. The code first generates a random number between 1 and 100. Then, it prompts the user to guess the number. The do-while loop continues to iterate as long as the user's guess is not equal to the random number. Inside the loop, the code compares the user's guess to the random number and provides feedback ('Too low!' or 'Too high!'). When the user guesses correctly, the loop terminates, and a congratulatory message is displayed along with the number of attempts it took.
import java.util.Random;
import java.util.Scanner;
public class DoWhileGuessingGame {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(100) + 1; // Generate a random number between 1 and 100
Scanner scanner = new Scanner(System.in);
int guess;
int attempts = 0;
do {
System.out.print("Guess a number between 1 and 100: ");
guess = scanner.nextInt();
attempts++;
if (guess < randomNumber) {
System.out.println("Too low! Try again.");
} else if (guess > randomNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the number " + randomNumber + " in " + attempts + " attempts.");
}
} while (guess != randomNumber);
scanner.close();
}
}
Concepts Behind the Snippet
The core concept is the do-while
loop, which is a post-test loop. This means that the code inside the loop is executed at least once before the condition is checked. In this example, this ensures that the user is prompted to guess a number even if the random number was trivially guessable (e.g., 1, if the prompt started at 1). The Random
class is used for generating pseudo-random numbers. The Scanner
class is used for reading input from the console.
Real-Life Use Case
Do-while loops are useful in scenarios where you need to execute a block of code at least once, regardless of the initial condition. Examples include menu-driven programs where you need to display the menu options at least once before the user makes a selection, or validating user input where you need to prompt the user for input until a valid value is entered.
Best Practices
Interview Tip
Be prepared to explain the difference between a while loop and a do-while loop. The key difference is that a do-while loop executes the code block at least once, whereas a while loop might not execute at all if the initial condition is false.
When to Use Them
Use a do-while loop when you need to guarantee that a block of code is executed at least once, regardless of the initial condition. If you don't need this guarantee, a while loop might be more appropriate.
Alternatives
While loops can achieve the same result as a do-while loop, but often require a different code structure. For example, you can duplicate the code block inside the loop before the while loop starts. Recursive functions can sometimes be used, but are less efficient for simple iterative tasks.
Pros
Cons
FAQ
-
What happens if the condition in a do-while loop is always true?
If the condition in a do-while loop is always true, the loop will continue to execute indefinitely, resulting in an infinite loop. The program will likely crash or become unresponsive. -
Can I use a break statement inside a do-while loop?
Yes, you can use abreak
statement to exit the loop prematurely. When thebreak
statement is encountered, the loop terminates, and the program execution continues with the next statement after the loop. -
Can I use a continue statement inside a do-while loop?
Yes, you can use acontinue
statement to skip the rest of the current iteration and proceed to the next iteration. When thecontinue
statement is encountered, the program skips the remaining statements in the loop body and jumps to the condition check at the end of the loop.