Loops are one of the first real "superpowers" you get as a programmer — instead of writing the same line of code ten times, you write it once and let it repeat. In C++, the while loop is the simplest of the three loop types, and it's the one you reach for when you don't know in advance how many times something needs to run.
This guide covers everything you need: the syntax, how it actually executes step by step, real examples, the mistakes beginners make most often, and how it compares to do...while and for loops.
What Is a While Loop in C++?
A while loop repeatedly executes a block of code as long as a condition stays true. Think of it as telling the computer: "Keep doing this until I say stop."
while (condition) {
// code to execute
}
Here's what happens on every pass:
- C++ checks the
condition. - If it's
true, the code inside the{ }runs. - Once the block finishes, C++ jumps back and checks the condition again.
- This repeats until the condition becomes
false, at which point the loop stops and the program moves on.
Because the condition is checked before the loop body runs, a while loop is called an entry-controlled loop — if the condition is false the very first time, the body never executes at all.
A Simple First Example
#include <iostream>
using namespace std;
int main() {
int num = 1;
while (num <= 5) {
cout << num << endl;
num++;
}
return 0;
}
Output:
1
2
3
4
5
Walking through it:
numstarts at1.- C++ checks
num <= 5before every iteration. - Each time through, the loop prints
num, thennum++increases it by 1. - Once
numbecomes6, the condition is false, and the loop exits.
Key Characteristics of a While Loop
| Feature | What it means |
|---|---|
| Pre-check condition | The condition is tested before each iteration — the body might not run at all. |
| Indefinite iterations | You don't need to know the exact number of repetitions in advance. |
| Manual update required | You must change the condition variable yourself inside the loop, or it never ends. |
That last point is the source of almost every while-loop bug, so let's cover it properly.
Common Mistakes to Avoid
1. Forgetting to Update the Condition (Infinite Loop)
int num = 1;
while (num <= 5) {
cout << num << endl; // num never changes — this runs forever
}
If nothing inside the loop changes the value being tested, the condition stays true forever and the program hangs. Always make sure something in the loop body moves you toward the exit condition (num++, reading new input, etc.).
2. Off-by-One Errors
Mixing up < and <= is a classic bug:
while (i < 5) // runs for i = 0,1,2,3,4 → 5 iterations
while (i <= 5) // runs for i = 0,1,2,3,4,5 → 6 iterations
Be deliberate about which one you actually want.
3. Using an Unrelated or Mismatched Condition
Make sure the condition you're testing actually reflects what you're trying to accomplish. A condition that's technically valid C++ but logically disconnected from the task will produce a loop that runs the "wrong" number of times without ever crashing — which makes it harder to spot.
Practical Examples
Example: Validating User Input
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age (1-100): ";
cin >> age;
while (age < 1 || age > 100) {
cout << "Invalid input. Try again: ";
cin >> age;
}
cout << "Thank you! Your age is " << age << "." << endl;
return 0;
}
This keeps asking until the user enters a valid number — a textbook use case for while, since you have no idea how many bad attempts the user will make.
Example: Running Total
#include <iostream>
using namespace std;
int main() {
int num, sum = 0;
cout << "Enter numbers to add (0 to stop): ";
while (true) {
cin >> num;
if (num == 0) break; // exits the loop
sum += num;
}
cout << "Total sum is " << sum << "." << endl;
return 0;
}
Example: Simple Password Check
#include <iostream>
#include <string>
using namespace std;
int main() {
string password;
while (password != "letmein") {
cout << "Enter password: ";
cin >> password;
if (password != "letmein") {
cout << "Wrong password. Try again." << endl;
}
}
cout << "Access granted!" << endl;
return 0;
}
Example: Countdown Timer
#include <iostream>
#include <unistd.h> // for sleep()
using namespace std;
int main() {
int countdown = 10;
while (countdown > 0) {
cout << "Countdown: " << countdown << " seconds remaining..." << endl;
sleep(1);
countdown--;
}
cout << "Time's up!" << endl;
return 0;
}
Controlling a While Loop: break and continue
Two keywords give you finer control over a running loop:
breakexits the loop immediately, skipping any remaining iterations.continueskips the rest of the current iteration and jumps straight to the next condition check.
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 10) {
i++;
if (i == 5) continue; // skip printing 5
if (i == 8) break; // stop the loop entirely at 8
cout << i << endl;
}
return 0;
}
Output: 1 2 3 4 6 7
Nested While Loops
A while loop can contain another while loop — useful for grids, tables, or comparing pairs of values.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
cout << "i=" << i << " j=" << j << " ";
j++;
}
cout << endl;
i++;
}
return 0;
}
Each inner loop fully completes before the outer loop moves to its next iteration — this is what produces a grid-like output.
while vs do...while: What's the Difference?
C++ has a close cousin of while called do...while. The difference is when the condition is checked:
while |
do...while |
|
|---|---|---|
| Condition checked | Before the body runs | After the body runs |
| Minimum executions | 0 (may never run) | Always at least 1 |
| Syntax | while (cond) { } |
do { } while (cond); |
int num = 10;
// while: body never runs, since condition is false immediately
while (num < 5) {
cout << num << endl;
}
// do...while: body runs once regardless, THEN checks condition
do {
cout << num << endl;
} while (num < 5);
Use do...while when you need the code to run at least once no matter what — a common example is displaying a menu before checking if the user wants to exit.
while vs for: Which Should You Use?
Both loop indefinitely based on a condition, but they suit different situations:
- Use
forwhen you know the number of iterations ahead of time (looping through an array of fixed size, counting 1 to 10). - Use
whilewhen the number of iterations depends on something that isn't known in advance — user input, a network response, a sensor reading, or any condition that could go either way.
// for: exact number of iterations known
for (int i = 0; i < 10; i++) { /* ... */ }
// while: unknown number of iterations
while (cin >> value) { /* keep reading until input stops */ }
When to Choose a While Loop
Reach for a while loop when:
- You don't know the exact number of iterations upfront.
- The loop needs to break based on a dynamic condition (user input, external data, a sensor, etc.).
- You want the flexibility to check any custom condition, not just a counter.