Java do while Loop

h‮w//:sptt‬ww.theitroad.com

In Java, the do-while loop is similar to the while loop, with the main difference being that the do-while loop executes the loop body at least once before checking the loop condition. This means that the loop body is always executed at least once, even if the condition is initially false.

Here is the basic syntax of the do-while loop in Java:

do {
    // code to execute for each iteration
} while (condition);

The do-while loop has two parts:

  • Loop body: This is the code that is executed in each iteration of the loop.
  • Condition: This is the test that is performed at the end of each iteration. The loop continues as long as this condition is true.

Here is an example that uses the do-while loop to print the numbers from 1 to 10:

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 10);

In this example, the loop starts with i being initialized to 1. The loop body prints the value of i for each iteration, and increments the value of i by 1 at the end of each iteration. The loop continues as long as i is less than or equal to 10. Since the loop body is executed at least once, the number 1 is printed to the console before the loop condition is checked.

You can also use the do-while loop to read input from the user or to wait for a specific condition to be true. Here is an example that uses the do-while loop to read integers from the user until the user enters a negative number:

Scanner scanner = new Scanner(System.in);

int number;
do {
    System.out.print("Enter a number (negative to quit): ");
    number = scanner.nextInt();
    System.out.println("You entered: " + number);
} while (number >= 0);

In this example, the loop reads integers from the user until the user enters a negative number. The loop checks whether the entered number is non-negative, and if it is, it prints the entered number to the console. The loop continues as long as the entered number is non-negative, and terminates when the user enters a negative number. Since the loop body is executed at least once, the user is prompted to enter a number even if the first number entered is negative.