Java do-While Loop

18-Sep-2024

Learn how to use the do-while loop to execute tasks at least once in Java programs

The do-while loop is a control flow statement in Java that repeatedly runs a block of code if a particular condition is met. Because the condition is tested at the end of the loop, the do-while loop ensures that the block of code is performed at least once, which sets it apart from other loops (such as for and while).


Syntax :



do {
// statements
} while(condition);


First, do body statements are executed then the condition will check. If the condition is true then again execute the do body statements. This process is repeated until the condition is false. In do-while loop if the first conditon will false. If the first condition of the do-while loop is false, the do body code will still be executed once


Flow Chart:




Example:


/**
 * Java do-While Loop Example
 */
public class JavaExample {

    public static void main(String[] args) {
       
      int i= 0;
      do{
        System.out.println("Do While Work Here : " +i);
        i=i+1;
      }while(i<10); // Condition Work Here
       
    }
   
}



Output:




Do WHile Work Here : 1
Do WHile Work Here : 2
Do WHile Work Here : 3
Do WHile Work Here : 4
Do WHile Work Here : 5
Do WHile Work Here : 6
Do WHile Work Here : 7
Do WHile Work Here : 8
Do WHile Work Here : 9



Comments