Understanding Java's Do/While Loop with Examples

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Introduce Java Do/While Loop and give examples

Answer:

The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The key feature of the do-while loop is that it guarantees that the code block will be executed at least once, even if the condition evaluates to false on the first check. This is because the condition is evaluated after the code block is executed.

Syntax of do-while Loop

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

Key Points:

  • The code inside the do block is executed once before the condition is tested.
  • After executing the block, the condition is evaluated.
  • If the condition is true, the loop continues; if false, the loop terminates.

Example 1: Basic do-while Loop

Here’s a simple example that demonstrates a do-while loop that prints numbers from 1 to 5:

public class DoWhileExample {
    public static void main(String[] args) {
        int number = 1;

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

Output:

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

Example 2: User Input with do-while Loop

In this example, we will use a do-while loop to repeatedly ask the user for input until they enter a specific value (e.g., "exit").

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input;

        do {
            System.out.print("Enter a command (type 'exit' to quit): ");
            input = scanner.nextLine();
            System.out.println("You entered: " + input);
        } while (!input.equalsIgnoreCase("exit"));

        System.out.println("Exiting the program.");
        scanner.close();
    }
}

Output:

Enter a command (type 'exit' to quit): hello
You entered: hello
Enter a command (type 'exit' to quit): exit
You entered: exit
Exiting the program.

Example 3: Summing Numbers Until a Condition is Met

In this example, we will use a do-while loop to sum numbers until the user enters a negative number.

import java.util.Scanner;

public class SumExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        int number;

        do {
            System.out.print("Enter a number (negative to stop): ");
            number = scanner.nextInt();
            if (number >= 0) {
                sum += number;
            }
        } while (number >= 0);

        System.out.println("Total sum: " + sum);
        scanner.close();
    }
}

Output:

Enter a number (negative to stop): 5
Enter a number (negative to stop): 10
Enter a number (negative to stop): -1
Total sum: 15

Conclusion

The do-while loop is a useful construct in Java for scenarios where you want to ensure that a block of code runs at least once before checking a condition. It is particularly handy for user input scenarios and when the initial execution of the loop body is necessary before any condition checks.