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;
  • expression is 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

  1. n starts at 10.
  2. The condition n > 0 is checked.
  3. If true → print n, then decrease it by one.
  4. When n reaches 0 → condition is false → loop stops.
  5. 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.