🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Do While Loop

C++ Do-While Loop Overview

The do-while Loop in C++:

The do-while loop in C++ is similar to the while loop, but with a key difference: the do-while loop guarantees that the loop body is executed at least once, even if the condition is initially false. The syntax of a do-while loop is as follows:


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

Here's an example of a simple do-while loop that prints the numbers from 1 to 5:


#include <iostream>

int main() {
    int i = 1;

    do {
        std::cout << i << " ";
        ++i;  // Increment the loop control variable
    } while (i <= 5);

    return 0;
}

In this example, the loop will print the numbers 1 to 5, just like the while loop. The key difference is that the condition i <= 5 is checked after the first execution of the loop body, ensuring that the loop body is executed at least once.

The output of this program will be:


1 2 3 4 5

Here's another example that demonstrates the use of do-while in a menu-driven program:


#include <iostream>

int main() {
    char choice;

    do {
        std::cout << "1. Print Hello\n";
        std::cout << "2. Print Goodbye\n";
        std::cout << "3. Exit\n";
        std::cout << "Enter your choice: ";
        std::cin >> choice;

        switch (choice) {
            case '1':
                std::cout << "Hello!\n";
                break;

            case '2':
                std::cout << "Goodbye!\n";
                break;

            case '3':
                std::cout << "Exiting the program.\n";
                break;

            default:
                std::cout << "Invalid choice. Please try again.\n";
        }

    } while (choice != '3');

    return 0;
}

In this example, the menu is displayed, and the user is prompted to enter a choice. The loop continues to display the menu and process choices until the user chooses to exit by entering '3'.

Use do-while when you want to ensure that a certain block of code is executed at least once, regardless of the initial condition.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.