Friday, April 17, 2009

do-while Loop

do-while looping construct

As we have seen in previous tutorial of while loop that if the controlling expression is false then the loop will not execute at all.However in some situations you may need that loop must at least execute once.do-while loop does just that .The do-while loop executes atleast once even if the controlling expression is false.The reason is that the controlling expression is placed at bottom of loop after body of loop.

Syntax:-

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

Thus,each iteration in do-while loop first executes the body then evaluates the conditional expression.If the boolean value is true then loop continues else terminates.

Example:-

int i=0;
do
{
System.out.println("Loop completes :"+(++i)+"times");
}while(i<5);

The output produced by above code snippet is:-

Loop completes :1times
Loop completes :2times
Loop completes :3times
Loop completes :4times
Loop completes :5times


NOTE:- The do-while loop is particularly useful in cases where menu selection is done.Where you need atleast once the loop to execute.Because in the end you wish to check whether user have entered a valid choice or not.This can be performed easily through do-while loop.

IMPORTANT:-Never forget to place a semicolon at the end of while in the do-while construct that is

do
{
}while(condition); //semicolon is must remember

Go to :-
Home
Control Statements
Operators

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP