The do...while loop

The syntax of the do...while loop is:

do
{
}while();

Let's consider the following example, where we want to print the numbers from 20 to 30:

    int j=20;
do
{
j++;
}while(j<30); // 1 loop of execution is guaranteed

The preceding code will print 20, 21, 22 until 29 as the output. Thus, first it executes and then it compares. 

The basic difference between the while and do...while loop is that the while loop will not execute without evaluating the Boolean expression, and the do...while loop first executes for one loop and then evaluates to run for more loops. 

Let's consider the following example, where the value of the variable is greater than 30:

int j=20;
do
{
j++;
}while(j>30); // 1 loop of execution is guaranteed

Here, the output will be 20, while the script after that will be terminated because, as mentioned earlier in this section, in the do...while loop, execution of one loop is guaranteed. If you run same logic in this while loop, even for the first time, it will not run.

So, in the next section, we will try to do one exercise based on the for loop, the while loop, the do...while loop, and the if condition. These programs will be good hands-on learning for understanding the loops.

In the next section, we will learn how the nested loops work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.187