Β 

πŸ” do-while loop in Java

When you want your code to run at least once, no matter what, the do-while loop is your best option. Unlike while and for, which check conditions before executing, the do-while loop checks the condition after running the code block.

This makes it perfect for menus, input validation, and interactive programs. πŸš€


🧐 What is a do-while loop?

A do-while loop executes a block of code once before checking the condition. Then, it continues running as long as the condition is true.

πŸ‘‰ Syntax:

do {
    // Code to be executed
} while(condition);

πŸ” How it Works

1️⃣ Code block executes once (even if condition is false).
2️⃣ Condition is checked.
3️⃣ If true β†’ loop repeats.
4️⃣ If false β†’ loop stops.

βœ… Example 1: Print Numbers from 1 to 5

int i = 1;
do {
    System.out.println("Number: " + i);
    i++;
} while(i <= 5);

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

πŸš€ Why use do-while loop?

βœ”οΈ Ensures code runs at least once.
βœ”οΈ Great for menu-driven programs.
βœ”οΈ Useful for user input validation.


⚑ Popular Examples of do-while loop

1️⃣ User Input Menu

Scanner sc = new Scanner(System.in);
int choice;
do {
    System.out.println("1. Play");
    System.out.println("2. Settings");
    System.out.println("3. Exit");
    System.out.print("Enter your choice: ");
    choice = sc.nextInt();
} while(choice != 3);

2️⃣ Guess the Number Game

int secret = 7;
int guess;
Scanner sc = new Scanner(System.in);
do {
    System.out.print("Guess the number (1-10): ");
    guess = sc.nextInt();
} while(guess != secret);

System.out.println("πŸŽ‰ Correct! You guessed it!");

3️⃣ Execute Once Even if Condition is False

int num = 10;
do {
    System.out.println("This runs once!");
    num++;
} while(num < 0);

Output:

This runs once!

πŸ’‘ Pro Tips

βœ… Perfect for menus, input-driven apps, and games.
βœ… Always ends with a semicolon (;) β†’ don’t forget it!
βœ… Be careful with conditions β†’ or you’ll end up in an infinite loop.

πŸ”‘ Difference between while and do-while

Feature while loop do-while loop
Condition check Before code runs After code runs
Minimum execution 0 times (if false initially) 1 time (always executes once)
Use case Unknown iterations Menus, input validation

Β 

βœ… In short:
The do-while loop is the go-to loop when you need the code to run at least once, making it highly useful in interactive and menu-based Java programs.

Β