DO WHILE LOOP

Dev Frank
3 min readJan 18, 2024

--

It is different from other loop statements. As you know for loop and while loop are entry control loop.

Do while is an exit control loop.

WHAT DOES THIS MEAN?

While we are exiting from the loop, that’s when the condition will be checked.

SYNTAX OF DO WHILE LOOP

do
{
// statement to be executed within the loop
// Update/Modify; (Increment & Decrement)
}while (condition);

NB: The Update/Modify can be anywhere within the loop, it doesn’t necessarily mean it has to be after the statement(s)

Here we have to note the semi-colon( ; ) after the while in the do-while loop. In do-while, we observe the semi-colon after the while statement, but in while loop we don’t have to put the semi-colon.

The do-while loop works this way:

We are not going to check any condition, the control will enter the do-block. Whatever you’ve written in the do-block it will be executed, after that condition will be checked.

If the condition is true, it will enter the do-loop and evaluate the statement(s) in it. If the condition is false definitely the control goes out of the loop.

In do-while loop the statement in the do-block will always be printed at least once. This means even though the condition is false a statement is always printed.

That’s why do-while loop is called an exit control loop.

Example

#include <stdio.h>
int main(void)
{
int x = 4;

do
{
printf("Happy\n");
x++;
}while(x <= 10);

return(0);
}

A variable x was declared and initialized with the value 4. Entering the do-while loop, the statement “Happy” will be evaluated followed by a newline.

Then x will be incremented having a value of 5, then the while condition will be tested. Since 5 is less than 10, the control goes inti the while loop and prints the statement “Happy” followed by a newline.

After that x is incremented to 6, since 6 is less than 10 the do statement will be evaluated and then x will be incremented to 7, the while loop will be evaluated. This loop keeps on going till x becomes 11, then it goes out of the loop.

The do-while loop is well-suited for situations where a program needs to perform certain actions at least once. It executes unconditionally for the first iteration and continues to run as long as the termination condition or test expression evaluates to true.

Once the termination condition becomes false, the do-while loop concludes its execution. If the termination condition evaluates to true, the loop may iterate again, and this process repeats until the condition becomes false.

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.