do while loop
A do while loop is a control structure that allows you to repeat a
series of instructions over and over again. A do while loop is a
post-test loop, since the boolean expression is evaluated after
the loop executes once. Do while loops are especially useful if
you know ahead of time that a loop should execute at least one time.
For example, login screens should execute at least one time, but may require more
passes through the loop if the user enters a wrong login or password.
Example:
// The following code prints out 0 1 2 3 4 done
// Here are the steps executed:
// Step 1: int i=0; creates a variable called i and sets the value to 0
// Step 2: Execute the instructions in the body of the loop
// System.out.print(i+" ");
// i++;
// Step 3: i<5 is evaluated and if true, go to step 2
// if false, exit (terminate) the loop, and continue with the
// next instruction after the loop body
int i=0;
do
{
System.out.print(i+" ");
i++;
} while (i<5);
System.out.print("done");
// note that 2 instructions are executed each time through the loop
// the braces { } are used to block off the body of the loop
More Examples:
// prints HelloHelloHellodone
int i=0;
do
{
System.out.print("Hello");
i++;
} while(i<3);
System.out.print("done");
// prints HelloHelloHellodone
int i=1;
do
{
System.out.print("Hello");
i++;
} while(i<=3);
System.out.print("done");
// prints HelloByeHelloByeHelloByedone
int i=1;
do
{
System.out.print("Hello");
System.out.print("Bye");
i++;
} while(i<=3);
System.out.print("done");
// prints
Hello
Bye
Hello
Bye
Hello
Bye
done
int i=1;
do
{
System.out.println("Hello");
System.out.println("Bye");
i++;
} while(i<=3);
System.out.print("done");
// prints
HelloBye
HelloBye
HelloBye
int i=1;
do
{
System.out.print("Hello");
System.out.println("Bye");
i++;
} while(i<=3);
// prints
1 10
2 20
3 30
int i=1;
do
{
System.out.println(i + " " + i*10);
i++;
} while(i<=3);