C++ while Loop
In this page:
Basic while Loop
A while loop repeatedly runs its body for as long as its condition stays true, checking that condition again before every single iteration — including before the very first one, so if the condition starts false, the loop body never runs at all. This makes while the right choice when you don't know in advance exactly how many times you'll need to repeat something.
Example: Basic while Loop
#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << count << std::endl;
count++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Decrementing Loop Conditions
Subtracting from a loop counter each iteration, like count-- inside the loop, lets you count downward toward a target instead of upward, which is exactly how countdown timers and reverse iteration through data are typically implemented. The loop's condition then usually checks for reaching zero or some lower bound.
Example: Decrementing Loop Conditions
#include <iostream>
int main() {
int count = 5;
while (count > 0) {
std::cout << count << std::endl;
count--;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Boolean Flags for Loop Control
Using a boolean variable as the loop's condition, such as while (keepGoing), lets code inside the loop body decide dynamically whether iteration should continue by changing that flag's value. This is a common pattern for loops whose stopping point depends on some runtime event rather than a simple counter.
Example: Using Boolean Flags for Loop Control
#include <iostream>
int main() {
bool keepGoing = true;
int count = 0;
while (keepGoing) {
std::cout << count << std::endl;
count++;
if (count >= 3) {
keepGoing = false;
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Numeric Limit Iterations
Multiplying or dividing a loop variable each pass, rather than adding a fixed amount, produces exponential rather than linear progress — useful for algorithms like binary search that repeatedly halve a search range, or for simulating compounding growth over time.
Example: Numeric Limit Iterations
#include <iostream>
int main() {
int value = 1;
while (value < 100) {
std::cout << value << std::endl;
value *= 2;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using the break Statement
Calling break inside a while loop immediately exits the loop entirely, skipping any remaining iterations and jumping straight to the code right after it. This is useful for stopping early the moment a specific condition is found, rather than continuing to check the loop's main condition on further passes that would be wasted work.
Example: Using the break Statement
#include <iostream>
int main() {
int count = 0;
while (count < 10) {
if (count == 3) {
break;
}
std::cout << count << std::endl;
count++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: