The while Loop
The while loop is the simplest loop in C++. It repeatedly executes a statement or block as long as a condition is true.
Syntax
while (expression)
statement;expressionis evaluated before every iteration.- If it’s
true, the loop executes the statement. - If it’s
false, the loop ends, and the program continues afterward.
Example: Countdown
// custom countdown using while
#include <iostream>
using namespace std;
int main() {
int n = 10;
while (n > 0) {
cout << n << ", ";
--n;
}
cout << "liftoff!\n";
}Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
How It Works
nstarts at 10.- The condition
n > 0is checked. - If
true→ printn, then decrease it by one. - When
nreaches 0 → condition isfalse→ loop stops. - Program continues after the loop.
Important
Infinite loop happens when the loop condition always stays true. For example, without --n, the loop would never end. Make sure that the condition eventually becomes false.