C++•Loops
C++ While and Do-While Loops with Examples
Use while loops when the iteration count depends on dynamic runtime conditions.
Syntax
while (condition) {}
do {} while (condition);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| while | Loop | Tests condition before running loop body. |
| do-while | Loop | Executes body at least once before testing condition. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
int main() {
int countdown = 3;
std::cout << "--- While Loop Countdown ---\n";
while (countdown > 0) {
std::cout << "T-minus " << countdown << "...\n";
--countdown;
}
std::cout << "Liftoff! 🚀\n\n";
// do-while executes once even if initial condition is false
int runOnce = 0;
do {
std::cout << "do-while body executed (runOnce = " << runOnce << ")\n";
++runOnce;
} while (runOnce < 1);
return 0;
}Expected Output:
--- While Loop Countdown --- T-minus 3... T-minus 2... T-minus 1... Liftoff! 🚀 do-while body executed (runOnce = 0)
How It Works: Step-by-Step
- Lines 6-9: Decrements counter and terminates when countdown reaches 0.
- Lines 14-17: do-while executes block once before evaluating condition.
Key Concepts
- The while loop re-checks condition at the start of every cycle.
- do-while is ideal for input validation prompts that must run at least once.
- Ensure loop condition variables are properly updated inside the body.
Common Mistake: Placing a semicolon immediately after while(condition);
A semicolon creates an empty loop body, creating an immediate infinite loop.
❌ Incorrect
while (x > 0); { --x; } // Infinite loop: body is empty statement!✅ Correct
while (x > 0) { --x; }Related C++ Tutorials & Compiler
C++ For Loops and Range-Based For Loops (C++11)
Master traditional counter loops and modern C++11 range-based for loops over collections.
C++ Break and Continue Loop Control Statements
Alter standard loop iteration using break and continue in C++.
C++ If...Else Statements and Boolean Logic with Examples
Learn decision-making structures in C++ with if, else if, else, and C++17 init-statements.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.