C++ ProgrammingProgramming

C++ Do While Loop Control Structure

Introduction

The do-while loop in C++ is similar to the while loop, but with one key difference:
πŸ‘‰ The loop body executes at least once, even if the condition is false initially.

That’s why it’s called an exit-controlled loop.

Syntax

do {
    // statements
} while (condition);
  • Loop executes body first.
  • Then condition is tested.
  • If true β†’ repeat body. If false β†’ exit.

Working of Do-While Loop

  1. Run loop body once.
  2. Test the condition.
  3. If true β†’ repeat body β†’ step 2.
  4. If false β†’ exit loop.

Example: Menu-driven program using Do-While

#include <iostream>
using namespace std;

int main() {
    int choice;
    do {
        cout << "Menu:\n";
        cout << "1. Say Hello\n";
        cout << "2. Say Bye\n";
        cout << "3. Exit\n";
        cout << "Enter choice: ";
        cin >> choice;

        switch (choice) {
            case 1: cout << "Hello!\n"; break;
            case 2: cout << "Bye!\n"; break;
            case 3: cout << "Exiting...\n"; break;
            default: cout << "Invalid choice!\n";
        }
    } while (choice != 3);

    return 0;
}

Key Points

  • Exit-controlled loop β†’ executes at least once.
  • Condition is tested after the body.
  • Useful in menu-driven programs or situations where the first run must always happen.

Differences Between While and Do-While

FeatureWhile LoopDo-While Loop
Condition checkBefore loop body (entry-check)After loop body (exit-check)
Execution countMay run 0 timesRuns at least once
Use caseRepeat until condition is trueMenu systems, input validation

Tips

  • Always terminate the do…while with a semicolon (;) after the condition.
  • Don’t confuse it with while β€” the placement of condition is the key difference.

Leave a Reply

Your email address will not be published. Required fields are marked *