Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of the do-while Loop
3.
How does a do-While loop execute?
4.
Example
4.1.
C++
5.
Flow diagram of the do-while loop 
6.
Examples of do while loop in C++
6.1.
Example 1: Basic Counter
6.2.
C++
6.3.
Example 2: User Input Validation
6.4.
C++
6.5.
Example 3: Password Retry Mechanism
6.6.
C++
7.
Frequently Asked Questions
7.1.
What is the main difference between a while loop and a do-while loop?
7.2.
Can a do-while loop execute only once?
7.3.
Is it possible to exit a do-while loop in the middle of execution?
8.
Conclusion
Last Updated: Jun 12, 2024
Easy

Do While Loop In C++

Author Pallavi singh
0 upvote

Introduction

A do-while loop in C++ is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop will first execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. This is different from a while loop, as in this condition is checked first before executing the code block. 

Do While Loop In C++

In this article, we will cover the syntax of a do-while loop, how it executes, a flow diagram which will show its working, & some examples to help you understand its usage.

Syntax of the do-while Loop

The syntax of a do-while loop in C++ is as follows:
do {
// code block to be executed
}
while (condition);


Here, the do keyword is used to start the loop, followed by the code block to be executed inside curly braces {}. After the code block, the while keyword is used, followed by the condition in parentheses (). The semicolon ; is used to end the loop.

Note : It's important to note that the code block will execute at least once, even if the condition is false from the start. This is because the condition is checked after the code block has been executed.

How does a do-While loop execute?

A do-while loop in C++ executes in the following manner:

  1. The code block inside the loop is executed once, regardless of the condition.
     
  2. After the code block is executed, the condition is evaluated.
     
  • If the condition is true, the code block is executed again.
     
  • If the condition is false, the loop terminates & the program control moves to the next statement after the loop.
     
  1. Steps 1 & 2 are repeated until the condition becomes false.

Example

  • C++

C++

#include <iostream>
#include <vector>
#include <algorithm>

int main()

{

int i = 1;

do {

cout << i << " ";

i++;

}

while (i <= 5);

return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output: 

1 2 3 4 5


In this example, the loop starts with i = 1. The code block is executed, printing the value of i & incrementing it by 1. After the first iteration, i becomes 2. The condition i <= 5 is then checked. Since it is true, the loop continues. This process repeats until i becomes 6, at which point the condition becomes false, & the loop terminates.

Flow diagram of the do-while loop 

Flow diagram of the do-while loop

The flow diagram illustrates the following steps:

  1. The code block is executed once unconditionally.
     
  2. The condition is checked.
     
  • If the condition is true, the flow goes back to the code block, & steps 1-2 are repeated.
     
  • If the condition is false, the loop ends, & the program continues with the next statement after the loop.

Note : This visual representation helps in understanding how the do-while loop works, with the code block always being executed at least once before the condition is checked.

Examples of do while loop in C++

Example 1: Basic Counter

In this simple example where a do-while loop is used to count from 1 to 5. This shows how the loop ensures that the code inside is executed at least once, regardless of the condition.

  • C++

C++

#include <iostream>

using namespace std;

int main() {

   int count = 1;

   do {

       cout << "Count: " << count << endl;

       count++;

   } while (count <= 5);

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output: 

1 2 3 4 5


In this code, even if the initial value of count was greater than 5, the loop body would still execute once, displaying the count.

Example 2: User Input Validation

A common use of the do-while loop is to keep prompting the user for input until a valid response is received. This example demonstrates asking the user for a 'Y' or 'N' response, repeating the request until a valid input is entered.

  • C++

C++

#include <iostream>

using namespace std;

int main() {

   char response;

   do {

       cout << "Continue? (Y/N): ";

       cin >> response;

       response = toupper(response); // Converts character to uppercase

   } while (response != 'Y' && response != 'N');

   cout << "You entered " << response << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

Continue? (Y/N): Y
You entered Y

This example illustrates the loop’s usefulness in scenarios where at least one execution of the code is necessary to initiate a process or validate conditions.

Example 3: Password Retry Mechanism

Do-while loops can also be effective in implementing retry mechanisms, such as when a user enters a password incorrectly. The loop continues until the user enters the correct password.

  • C++

C++

#include <iostream>

#include <string>

using namespace std;

int main() {

   string password;

   do {

       cout << "Enter your password: ";

       cin >> password;

   } while (password != "secret");

   cout << "Access granted." << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Enter your password: hello
Enter your password: secret
Access granted.


In this scenario, the loop ensures the password prompt is repeated until the correct password is entered, enhancing security measures in applications.

Frequently Asked Questions

What is the main difference between a while loop and a do-while loop?

A while loop checks the condition before executing the loop body, whereas a do-while loop executes the loop body first before checking the condition.

Can a do-while loop execute only once?

Yes, if the condition evaluates to false after the first execution, the do-while loop will terminate and not repeat.

Is it possible to exit a do-while loop in the middle of execution?

Yes, you can use the break statement within the loop to exit prematurely, regardless of the condition.

Conclusion

In this article, we have learned about the do-while loop in C++. We discussed its syntax, how it executes, & saw a flow diagram to visualize its working. We also looked at couple of examples to understand how do-while loops works. The do-while loop is a powerful control flow statement that allows you to repeat a block of code based on a condition, with the code block being executed at least once before the condition is checked. It is a useful tool in a condition where you need help with repetitive tasks that require at least one execution.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass