The do while loop in C++ is similar to while loop with one important difference, the code block of do..while loop is executed once before the condition is checked. It checks its condition at the bottom of the loop, before allowing the execution of loop body for second time. The block of code is before the condition, so code will be executed at lease once.
Syntax of do while Loop
do { // Code to be executed } while (condition);In this construct, the block of code within the curly braces is executed first, and then the loop evaluates the specified condition. If the condition is true, the loop repeats; if false, the loop bids farewell.
do while Loop Syntax Description
- condition : The condition expression in do while loop is a boolean expression. Condition expression is evaluated after code block of do-while loop. It must evaluate to true or false value(In C++, all non-zero values are considered as true and zero is considered as false).
- statement(s) : do while loop's body can contain zero or more number of statements. Unlike for and while loop, all statements inside do-while loop will gets executed atleast once.
- Unlike while loop, there is semicolon in the end of while(condition); in do..while loop.
Flow diagram of do while Loop in C++
How do while loop works ?
- First do while loop execute the statements inside body of the loop.
- Then, the condition expression is tested. If the condition expression evaluates to true then body of do..while loop is executed.
- If the condition expression evaluates to false then do..while loop is terminated and control goes to the next statement after do..while loop.
C++ do..while Loop Example Program
#include <iostream> using namespace std; int main(){ int N, i, sum=0; cout << "Enter a positive number\n"; cin >> N; i = 1; do { // Below statements will execute atleast once sum+= i; //Incrementing loop control variable i++; } while(i <= N); cout <<"Sum of Integers from 1 to " << N << " = " << sum; return 0; }
Output
Enter a positive number 5 Sum of Integers from 1 to 5 = 15
Enter a positive number 7 Sum of Integers from 1 to 7 = 28
Advantages of Do-While Loops in C++
The do-while loop in C++ is like a resilient companion, offering unique advantages that set it apart from other loop constructs. Let's delve into the strengths of the do-while loop, understanding how its characteristics make it a valuable tool in certain scenarios.
- Guaranteed Initialization : The most distinctive feature of the do-while loop is its commitment to executing the block of code at least once before checking the loop condition. This guarantees the initialization of variables or execution of essential code segments before entering the loop.
- User-Friendly Input Validation : Do-while loops shine in scenarios requiring user input validation. By prompting the user at least once and repeating until valid input is provided, they enhance the user experience by guiding users through the correct input process.
#include <iostream> int main() { int userInput; do { std::cout << "Enter a positive number: "; std::cin >> userInput; } while (userInput <= 0); std::cout << "You entered: " << userInput; return 0; }
Here, the do-while loop ensures that the user inputs a positive number, providing a user-friendly and interactive input validation mechanism. - Input Processing Until Sentinel Value : Do-while loops excel in scenarios where input processing is required until a specific sentinel value is encountered. This pattern is common when reading data until the user signals the end of input.
#include <iostream> int main() { int value; int sum = 0; do { std::cout << "Enter a value (enter 0 to stop): "; std::cin >> value; sum += value; } while (value != 0); std::cout << "Sum of values: " << sum; return 0; }
The do-while loop here ensures that the loop body executes at least once, processing input until the user enters the sentinel value (0). - Simplified Infinite Loops : When creating infinite loops with an exit condition, the do-while loop offers a more straightforward structure. The condition can be placed conveniently within the loop, ensuring that the loop body executes before checking the exit condition.
do { // Code within the loop if (someCondition) { break; // Break out of the loop when necessary } } while (true);
This pattern ensures that the loop body executes at least once, simplifying the structure of an infinite loop.
Points to Remember about do while loop
- do…while loop is guaranteed to execute at least once.
- The condition expression in do while loop is a boolean expression. It must evaluate to true or false value(In C++, all non-zero values are considered as true and zero is considered as false).
- Unlike for loop, initialization statements, condition expression and update statements are on different line.
- Opening and Closing braces are not required for single statement inside do while loop code block.
For Example:
do
statement;
while(condition);
- We can also use infinite do while loops which will never terminate. You should add terminating condition using break statement in order to terminate infinite do while loop.
For Example:
do {
if(....){
break;
}
} while(1);
Best Practices for Using Do-While Loops
To harness the full potential of the do-while loop, it's wise to adhere to some best practices that ensure clarity, efficiency, and maintainability.
- Initialize Loop Control Variable : Always initialize the loop control variable before entering the do-while loop. This provides a known starting point for the loop.
int i = 0; do { // Code within the loop ++i; // Update the loop control variable } while (i < 5);
- Update Loop Control Variable Within the Loop : Ensure that the loop control variable is updated within the loop to prevent an infinite loop.
int i = 1; do { // Code within the loop ++i; // Update the loop control variable } while (i <= 5);
- Define Clear Exit Conditions : Ensure that the conditions specified in the do-while loop are clear and lead to an eventual exit. Vague or complex conditions can result in unintended behavior.
do { // Code within the loop } while (someCondition);
- Avoid Infinite Loops : Beware of infinite loops – those that never meet their exit conditions. Double-check your conditions and update expressions to prevent this coding abyss.
do { // Code within the loop if (someCondition) { break; // Break out of the loop when necessary } } while (true);
- Use for Loops for Count-Controlled Scenarios : While do-while loops are excellent for scenarios where the code should execute at least once, for count-controlled scenarios, consider using for loops for a more concise syntax.
for (int i = 0; i < 5; ++i) { // Code within the loop }