While & Do-While Loops
Overview
If you need to execute a block of code repeatedly, you use a loop. A while loop checks a condition BEFORE it executes the code. If the condition is true, it runs the block, then checks the condition again. It is perfectly designed for scenarios where you do not know how many times the loop needs to run (e.g., 'Keep reading network packets until the user disconnects').
A do...while loop flips the architecture. It executes the code block first, and checks the condition at the end. This mathematically guarantees that the code inside a do...while loop will ALWAYS execute at least once, regardless of the condition.
Syntax
// --- 1. THE WHILE LOOP ---
int count = 0;
// Checks condition FIRST
while (count < 3) {
std::cout << "Looping: " << count << "\n";
count++; // CRITICAL: Ensure the condition eventually becomes false!
}
// --- 2. THE DO-WHILE LOOP ---
int input;
// Executes code FIRST, checks condition LAST
do {
std::cout << "Enter a positive number: ";
std::cin >> input;
} while (input <= 0); // Notice the semicolon here!Common Pitfalls
- The Infinite Loop. If you forget to modify the variable that the condition relies on (e.g., forgetting
count++), the condition will remain true forever. The loop will run infinitely, instantly maxing out 100% of a CPU core and completely freezing your application. - Forgetting the semicolon at the end of a
do...whileloop. While standardifandwhileloops don't use semicolons after their conditions, the syntax ofdo { } while (condition);strictly requires a semicolon at the very end.
Interview Questions
while loop and a do...while loop?A while loop is a 'pre-test' loop; if the initial condition is false, the internal code is executed zero times. A do...while loop is a 'post-test' loop; the internal code is blindly executed exactly once before the condition is ever evaluated.
Real-World Example
Using a classic 'Infinite While Loop' (while(true)) combined with a custom breakout condition to drive the main event loop of a video game or server.
bool isGameRunning = true;
// The classic 'Game Loop'
while (isGameRunning) {
// 1. Process player input
char key = getInput();
// 2. Break out of the loop dynamically
if (key == 'Q') {
isGameRunning = false;
}
// 3. Render graphics
// renderEngine();
}Check Your Knowledge
Test your understanding of While & Do-While Loops with these quick questions.