Wednesday, October 07, 2015

do while loop

do-while

The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

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

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression.

If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.

Here is a reworked version of the “tick” program that demonstrates the do-while loop.

// Demonstrate the do-while loop.
class WLDoWhile
{
public static void main(String args[])
{
int n = 5;
do
{
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}

type following command in command prompt

javac WLDoWhile.java
java WLDoWhile

tick 5
tick 4
tick 3
tick 2
tick 1

As you just saw if the conditional expression controlling a while loop is initially false then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning.


No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)