Skip to main content

while, do/while, and Validation Loops

beginner10 min readLesson 14 of 204

Condition-first vs body-first loops, accumulators, input validation patterns, and infinite-loop hygiene.

while: as long as the condition holds

int cups = 0;
while (cups < 3) {
    std::cout << "refilling...\n";
    ++cups;               // forget this and the loop never ends
}

Use while when the number of repetitions is unknown in advance โ€” reading until end-of-file, searching until found, waiting for a condition.

do/while: check after the first try

std::string choice;
do {
    choice = ask_menu();      // body runs FIRST, at least once
} while (choice != "h" && choice != "q");

do/while is for "ask at least once, then re-ask while invalid" โ€” menu loops, retry prompts. If you never need the guaranteed first pass, plain while reads better.

Accumulators and search

Two patterns cover most loops you will write this year:

// accumulator
int total = 0;
for (int s : scores) total += s;

// first-match search
int first_below_60 = -1;
for (std::size_t i = 0; i < scores.size(); ++i) {
    if (scores[i] < 60) { first_below_60 = static_cast<int>(i); break; }
}

Module 8 replaces both hand-rolled versions with STL algorithms โ€” but write them by hand now; you cannot trust abstractions you have never built.

Infinite-loop hygiene

A while loop needs something inside it that moves the state toward the exit condition: ++cups, std::cin >> value, break. The sandbox kills runaway programs with a timeout and reports "timeout" โ€” if you see that verdict in a graded run, look for the missing step.

Now practice

While Practice: Search and ValidateA digit-sum loop, a first-match search, and a validation loop that keeps asking until sane.1 challenge ยท ยท ~25 min