Java From Beginner To Advanced

0% completed

Previous
Next
Java do...while loop

The do...while loop is similar to the while loop, but it guarantees that the code block executes at least once before the condition is checked. This loop is useful when you want the code to run initially, regardless of the condition, and then continue running as long as the condition remains true.

Syntax

do { // Code block to be executed } while (condition);
  • Code block: Contains the statements that will execute before checking the condition.
  • Condition: A boolean expression evaluated after the code block; if true, the loop repeats.

Execution Flow

Image
  • Step 1: The code block is executed unconditionally for the first time.
  • Step 2: After execution, the condition is evaluated.
  • Step 3: If the condition is true, the loop repeats and the code block is executed again.
  • Step 4: This process continues until the condition evaluates to false, at which point the loop terminates.

Example 1: Basic do...while Loop

Below is an example that demonstrates a do...while loop which prints a message at least once even if the condition is false.

Java
Java

. . . .

Explanation:

  • The code block prints the value of counter and then increments it.
  • Even though the condition counter < 10 is false after the first execution, the code block runs once because the condition is checked only after executing the block.

Example 2: Calculating a Sum with a do...while Loop

Below is an example that uses a do...while loop to calculate the sum of numbers from 1 to 5.

Java
Java

. . . .

Explanation:

  • The loop starts with number equal to 1.
  • The block adds number to sum and increments number.
  • The condition number <= 5 is evaluated after each execution.
  • The loop continues until number exceeds 5, and then prints the final sum.

The do...while loop is beneficial when you need to ensure that the code block executes at least once before evaluating the condition. Experiment with these examples to see how this loop can be used in scenarios where initial execution is necessary.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next