Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

The do-while loop

Same as for loop and while loop, do-while loop is also used to execute specific part of the program repeatedly.

The only difference is that the body of do-while loop is executed at least once even if the condition is false.

Syntax

do
{
    // programming
    // statements

}while(condition);

Flowchart

Java Programming Language do-while Loop Flowchart

Working

Java Programming Language do-while Loop Working

Step I –
          Program control enters directly into the body of do-while loop and executes it.

Step II –
         Control checks the condition. If the condition is true, program control executes the body of do-while loop once again.

This process goes on till condition does not become false.

To make condition false, we need to write some expression inside the body of do-while loop.

Example No. 1

class DoWhileLoopDemo1 
{
    public static void main(String args[]) 
    {
        int n;
        n = 1;
        do
        {
            System.out.println("John");
            n++;
        }while(n<=10);
    }
}

Output

John
John
John
John
John
John
John
John
John
John

Thus with the help of do-while loop in the above program, we have succeeded to print name 10 times by writing it just 1 time.

Example No. 2

class DoWhileLoopDemo2 
{
    public static void main(String args[]) 
    {
        int n;
        n = 1;
        do
        {
            System.out.print(n+" ");
            n++;
        }while(n<=10);
    }
}

Output

1 2 3 4 5 6 7 8 9 10

Here we have succeeded to print numbers 1 to 10 by writing line

System.out.print(n+"  ");

in do-while loop, just one time.

Leave a reply