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:
Post a Comment
Post a Comment