The do-while Statement and a Comparison of All Loop Types

We have learned about the while and for loops. In this lesson, we’ll learn about a new control structure known as the do-while loop.

Syntax

The syntax of a do-while loop in C++ is as follows:

do 
{ 
    statement(s); 
}
while( condition );

Working of the do-while loop

The do-while loop works such that the statement(s) inside the block ({ }) of do are executed first, and then the while condition is checked. If the condition is true, only then the block inside the do is executed again. This is repeated as long as the while condition is true.

The animation above starts with a variable a being initialized to 1. Then the control goes to the do block and a becomes equal to 3. Then the while condition in line 6 is checked. If it’s true (which it is since 3 < 5), then the do block is executed once again. After that the while condition is checked. This time the condition becomes false (since 5 is not less than 5). The control then goes to line 7 and a is printed.

Difference between the do-while and while loops

The difference between the do-while and while loops is that in the while loop, the condition is checked first. If that condition is true, only then is the body of the while loop executed. However, in do-while, the body written inside the do block { } is executed at least once, and then the condition is checked. If the condition is true, only then the body of the while loop is executed again and is repeated until the condition becomes false.

We can see in the example above that first, the hello message will be printed regardless of checking the condition, and then if the user enters y, then the message hello will be printed again. Otherwise, the loop will break.

When should we use do-while, while, and for?

  • We use a for loop when we know how many times we want to execute a statement.

  • We use a while loop when we want to execute a statement based on whether some condition is true or false.

  • We use a do-while loop when we want to execute a statement at least once and then as many times as we want based on whether a condition is true or not.