C++ do…while Loop

🔁 C++ do…while Loop

do…while loop ek exit-controlled loop hai, jisme loop body kam se kam ek baar zaroor execute hoti hai, chahe condition false hi kyon na ho.


🔹 1. Syntax

do {
// code
} while (condition);

👉 Note: while ke baad semicolon ; zaroori hota hai.


🔹 2. Basic Example

int i = 1;

do {
cout << i << " ";
i++;
} while (i <= 5);

Output:

1 2 3 4 5

🔹 3. Condition False but Loop Runs Once

int i = 10;

do {
cout << i;
} while (i < 5);

Output:

10

👉 Body ek baar execute hui.


🔹 4. Menu-Driven Program Example

int choice;

do {
cout << "\n1. Add\n2. Subtract\n3. Exit\n";
cout << "Enter choice: ";
cin >> choice;

if (choice == 1)
cout << "Addition Selected";
else if (choice == 2)
cout << "Subtraction Selected";

} while (choice != 3);


🔹 5. User Input Loop

int num;

do {
cout << "Enter number (0 to stop): ";
cin >> num;
cout << "You entered: " << num << endl;
} while (num != 0);


🔹 6. while vs do…while

while do…while
Entry-controlled Exit-controlled
May run 0 times Runs at least once
Condition first Code first

❌ Common Mistakes

do {
cout << "Hello";
} while (i < 5) // ❌ missing ;

✔ Correct:

} while (i < 5);

📌 Summary

  • do…while loop at least once execute hota hai

  • Menu & input validation ke liye best

  • Semicolon after while is mandatory

You may also like...