The while loop
- C++ course
- Beginner
- Lesson 43/116
- 4 min
Learn loops that run while a condition holds with while.
The while loop
The construct that repeats while a condition holds is the while loop. Its form is while (condition) { ... }; the condition is checked at the start of each iteration and, when false, the loop ends.
For example int count = 0; while (count < 3) { std::cout << count; count++; } prints 0, 1 and 2. You must write the increment yourself; forgetting it produces an infinite loop. while is preferred over for when the number of iterations is not known in advance.
while vs for
while and for can often replace each other. The rule of thumb: pick for when you know the number of iterations, while when you do not. while feels more natural when reading user input or going until the end of a file.
Writing while (true) creates an infinite loop; it keeps running until you exit with break. This pattern is common in menus and event loops. Used carelessly, however, it can freeze the program.
Practice Print 0, 1, 2 (while)
The count variable is set to 0. Inside a while (count < 3) loop print count with std::cout << count; and increase it with count++. The output must be 012.
Starter code
#include <iostream>
int main() {
int count = 0;
// Print 0, 1, 2 with while
return 0;
}Sample solution
#include <iostream>
int main() {
int count = 0;
while (count < 3) {
std::cout << count;
count++;
}
std::cout << std::endl;
return 0;
}Expected output
012
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each while part to its role
| Term | Meaning |
|---|---|
while (cond) |
Condition at top |
count++ |
Increment in body |
count < 3 |
Continue condition |
{ ... } |
Loop body |
2 What kind of loop is while (true)?
while (true) { ... }- Never runs
- Runs once
- Compile error
- Infinite loop Correct answer
Explanation: The condition is always true so the loop runs forever without a break.
3 Write the while condition
int count = 0;
while (____) { count++; }
int count = 0;
while (count < 3) { count++; }
Explanation: count < 3 is true for 0, 1 and 2.