java
  1. java-do-while-loop

Java Do-While Loop

Syntax

do {
   statement(s)
} while (condition);

Example

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

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8
Count: 9
Count: 10

Explanation

The do-while loop is similar to the while loop, with one key difference - it checks the condition at the end of the loop rather than the beginning. This means the loop will always execute at least once.

The structure of the do-while loop is as follows:

  1. The do keyword
  2. A set of statements to be executed
  3. The while keyword and a conditional statement in parentheses

If the conditional statement is true, the loop will execute again. If the conditional statement is false, the loop will exit and the program will continue.

Use

The do-while loop is useful when you want to execute a set of statements at least once, regardless of whether the initial condition is true or false. It can also be used in situations where you want to execute a set of statements until a certain condition is met.

Important Points

  • The do-while loop will always execute at least once.
  • The condition is checked at the end of the loop, rather than the beginning.
  • The loop will continue executing as long as the condition is true.

Summary

The do-while loop is a control flow statement in Java that allows a set of statements to be executed at least once before checking the condition. It is useful when you want to execute a set of statements until a certain condition is met or if you want to execute a set of statements regardless of the initial condition being true or false. When using this loop, be aware that the condition is checked at the end of the loop rather than the beginning.

Published on: