C++ do-while

🔂 C++ do-while Loop – Guaranteed One-Time Execution

The do-while loop is like the brave adventurer: it jumps into the task before checking the condition! 🧗‍♂️

It runs the code block once, then checks the condition to decide if it should run again.

🧠 Syntax of do-while Loop

do {
    // code to run at least once
} while (condition);

🔧 Example: Print Numbers 1 to 5

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << "i = " << i << endl;
        i++;
    } while (i <= 5);
    return 0;
}

Try It Now

📌 Key Point

Even if the condition is false from the start, the loop body will still execute once.

⚠️ Example: Run Once Even When False

#include <iostream>
using namespace std;

int main() {
    int i = 10;
    do {
        cout << "This runs once even though i = 10!" << endl;
    } while (i < 5);
    return 0;
}

Try It Now

🎯 When to Use do-while?

  • When you must run the code at least once
  • Perfect for menus, game loops, or user input retries

The do-while loop always gives your code a chance to shine—once, and maybe more! 🌟