5.4 — do-while loops

📘 Chapter 5⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Run at least once#

A do-while loop checks the condition at the end. So the code always runs at least once.

C++
int choice {};do{    std::cout << "1) Play\n2) Quit\nChoose: ";    std::cin >> choice;} while (choice != 1 && choice != 2);

The menu shows once, then repeats while the choice is not 1 or 2.

Watch out

Note the ; after while (...) at the end. A do-while needs it.

Tip

do-while is not used often. A while (true) with break usually does the same job and is easier to read.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.