Do-While Loop In Java

The While loop test condition before the loop is executed.Therefore,the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed.Such situation can be handled with the help of the do statement.Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom of the loop after executing it’s loop-body statements. This means that a do-while loop always executes at least once. The syntax of the do-while loop is:

    do

    {

         loop-body;

     }

while(condition);

 

Example:

 ……………………

……………………

i=1;

sum=0;

do

{

              i=i+2;

}

while(sum<40 || i<10);

………………………..

……………………….

 

the loop will be executed as long as one of the two relations is true.

 

Sample Program:-

 

class DoWhileTest

{

     public static void main(String args[])

     {

           int row,column,y;

           System.out.println(“Multiplication Table:”);

            row=1;

            do

            {

                     column=1;

                      do

                     {

                               y=row*column;

                              System.out.println(” “+y);

                             column=column+1;

                       }

                       while(column<=3);

                       System.out.println(“\n”);

                       row=row+1;

              }

              while(row<=3);

       }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s