Blog / October 5, 2023 / 2 mins read / By Suneet Agrawal

While and Do-While Loop in C++

Loops are fundamental constructs in programming that allow us to repeat a block of code multiple times. In C++, two commonly used loop structures are the while loop and the do-while loop. In this blog post, we’ll dive into these loops, understand their syntax, and provide examples to illustrate their usage.

The While Loop

The while loop is a conditional loop that repeats a block of code as long as a specified condition is true. Here’s the basic syntax:

while (condition) {
    // Code to be executed while the condition is true
}

Counting from 1 to 10

#include <iostream>

int main() {
    int i = 1;
    while (i <= 10) {
        std::cout << i << " ";
        i++;
    }
    return 0;
}

In this example, the while loop continues to execute as long as i is less than or equal to 10. It prints numbers from 1 to 10.

The Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once before checking the condition for continuation. Here’s the basic syntax:

do {
    // Code to be executed
} while (condition);

User Input Validation

#include <iostream>

int main() {
    int userChoice;
    
    do {
        std::cout << "Please enter a number between 1 and 5: ";
        std::cin >> userChoice;
    } while (userChoice < 1 || userChoice > 5);
    
    std::cout << "You entered a valid number: " << userChoice << std::endl;
    
    return 0;
}

In this example, the program repeatedly prompts the user for input until they enter a number between 1 and 5.

Key Differences between While and Do-While

While both while and do-while loops are used for repetitive tasks, they differ in when they check the loop condition:

  • In a while loop, the condition is checked before entering the loop. If the condition is initially false, the loop will not execute at all.
  • In a do-while loop, the condition is checked after executing the loop body once. This guarantees that the loop body will run at least once, even if the condition is false initially.

Conclusion

In C++, the while and do-while loops are essential tools for controlling program flow when you need to execute a block of code repeatedly based on a condition. Understanding the differences between these two loops and knowing when to use each is crucial for writing efficient and bug-free code. Practice with various examples to master their usage, and you’ll be well on your way to becoming a proficient C++ programmer.

Comments