Java do while loop

do-while

 

In do-while loop, the body of the loop will execute atleast once even if the conditional expression is false to begin with.

 

This is because, the conditional expression is at the bottom of the loop.

 

Syntax for do-while loop is:


do {
// body of loop
} while(condition);

 

Here, condition must be a boolean expression.

 

In each iteration, the body of the loop is executed first and then the conditional expression is evaluated. If the condition evaluates to true, the loop is repeated; otherwise, the loop terminates.

Here is an example of do-while loop :

 

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

Here is the output from the above program:
Count = 1
Count = 2
Count = 3
Count = 4

 

Now, let’s change the loop condition, so that it evaluates to false from the beginning:

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

 

The program when executed will print : Count =1
This is because, the do..while loop executes the body once before it evaluates the condition.

 

© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags