Java

Do-While Loop In Java

We spoke about the while loop in the last tutorial. We will talk about Java’s do-while loop in this lesson. While loop and do-while loop are similar, they differ in the following ways: While the condition is assessed in a while loop before the body of the loop is executed, it is evaluated in a do-while loop following the body of the loop.

Syntax of do-while loop:

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

How do-while loop works?

The statements inside the loop are executed first, after which the condition is assessed; if it returns true, control is passed to the “do” statement; otherwise, it goes to the next statement following the do-while.

do-while loop example

class DoWhileLoopExample {
    public static void main(String args[]){
         int i=10;
         do{
              System.out.println(i);
              i--;
         }while(i>1);
    }
}

Output:

10
9
8
7
6
5
4
3
2

Example: Iterating array using do-while loop

Here, we are using a do-while loop to go through an integer array while showing each member.

class DoWhileLoopExample2 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0
         int i=0;
         do{
              System.out.println(arr[i]);
              i++;
         }while(i<4);
    }
}

Output:

2
11
45
9

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button