A do-while loop is almost alike to the while loop, but in this loop, the test condition is not at the beginning of the loop structure but at the end.

There are two kinds of loop: Pre-test Loop and Post-test loop.

Loops like for-loop and while loop are Pre-Test Loops because the test condition is checked at the beginning of the loop, which means the loop will not run even for a single time if the test condition is found false.

Whereas the do-while loop is called the Post Test Loop. This means the block of statements inside the loop will be executed first and then the condition is checked. Naturally, you can understand the loop will run at least once even if the condition is not true.

The syntax for do-while loop:

do

{

//block of statements

}

while( <test condition>);

Let’s do the same task of printing 8 times “I Love Computers” yet again but this time using a do-while loop.

class Repeat
{
public static void main()
{
int i=1;
do
{
System.out.println("I Love Computers");
i++;
}while(i<=8);  
}
}

 

Similarly, let’s write a program to print the first ten multiples of 2, but this time using do-while loop:

class Multiple
{
public static void main()
{
int i=1;
int c=0;
do
{
c=2*i;
System.out.println(c);
i++;
}
while(i<=10);
}
}

Output:

2
4
6
8
10
12
14
16
18
20

Thus you can see you can write the same program in different ways using various looping structures.

You can also convert a loop of one kind into a looping construct of other kinds, simply by implementing the syntax of the loop construct correctly.

 

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019