do while Statement in C

The do-while loop is an exit-controlled loop in which first the body of a loop is executed and then the condition is checked. Now, if the condition is true then the statements are executed again. However, if the condition is False, the control is transferred to statement immediately after the body of loop. The condition can be any constant, variable or expression that evaluates to True or False.

The general syntax of do-while requires a counter variable to be initialized before do-while statement. Then within the condition, this counter variable needs to be checked against some value. The general flow of an exit- controlled loop is shown in figure 1.

Screenshot from 2020-07-16 16-41-11

Figure 1: General flow of an exit-controlled loop

This means the do-while construct has a condition part that decides whether the statements will be executed or not. Also, it has a counter variable to keep the count of number of times the statements are executed. However, this counter variable needs to be modified during iteration within the body of loop. The counter modification statement should be last statement of the body of the loop. The general syntax of while looping statement is as follows:

counter-initialisation;
do
{
statements;
counter-modification;
}

while ( condition );

One may argue why we should use such kind of a loop. The answer is simple. There are certain situations wherein we need it. For example, we want to get a number from user that is greater than 10. And if the number is less than or equal to 10, we should again ask for the number. The code snippet below shows how this can be done using a while loop.

int num;
printf(“Enter number? ”);
scanf(“%d”, &num);
while( num <= 10 )
{
printf(“Enter number? ”);
scanf(“%d”, &num);
}

In contrast, we can do this with lesser number of statements using do-while loop as shown in code snippet below.

int num;
do
{
printf(“Enter number? ”);
scanf(“%d”, &num);
}
while( num <= 10 )

It should be noted that the body of exit-controlled loops is executed at-least once. Hence, even if the condition is False in first iteration, the body of loop will be still executed at least once. In contrast, in entry controlled loops the body in every iteration will only be executed if condition is True. The code snippet below explains this clearly.

int x = 1;
do
{
printf(“I will be printed”);
}
while ( x < 0);