C++ While Loop

A while loop in C++ repeats a block of code as long as a given condition stays true. Unlike a for loop, which is built for counting a known number of iterations, a while loop is ideal when you don’t know in advance how many times you need to repeat something — for example, reading input until the user types “quit”, or dividing a number in half until it drops below 1. Understanding exactly when the condition is checked, and how to make sure it eventually becomes false, is the key to using while safely.

Overview / How It Works

A while loop consists of a boolean condition and a body. Before every single iteration — including the very first one — the compiler-generated code evaluates the condition. If the condition is true, the body executes once and control jumps back to re-check the condition. If the condition is false, the loop body is skipped entirely and execution continues with the statement after the loop. This means a while loop can execute zero times if its condition is false from the start — a key difference from the do-while loop, which always executes at least once.

Internally, at the machine level, a while loop compiles down to a conditional jump instruction (something like “compare and branch-if-false to the end label”) followed by the loop body and an unconditional jump back to the comparison. There is no hidden loop counter or extra memory allocated by the loop itself — any variables used in the condition (like a counter or a flag) must be declared and updated by you, either before the loop (for initialization) or inside the loop body (to eventually make the condition false). This is the single most important habit to build: every while loop needs (1) a variable initialized before the loop, (2) a condition that references that variable, and (3) code inside the body that changes the variable so the condition can eventually fail.

Syntax

while (condition) {
    // statements to repeat
}
  • condition — any expression that evaluates to true or false (or a value convertible to bool, like a non-zero integer). Checked before every iteration.
  • { } — the loop body. If it contains a single statement, the braces are technically optional, but including them is strongly recommended.
  • The loop repeats indefinitely until condition evaluates to false, or until a break, return, or goto exits it early.

The do-while Variant

C++ also offers do { ... } while (condition);, which checks the condition after running the body, guaranteeing at least one execution. Use it when the body must run once regardless of the condition (menus, input prompts, etc.).

#include <iostream>
using namespace std;

int main() {
    int n = 10;
    do {
        cout << "This runs at least once. n = " << n << endl;
        n++;
    } while (n < 5);
    return 0;
}

Output:

This runs at least once. n = 10

Even though n < 5 is false from the start (n is 10), the body still runs exactly once because do-while checks the condition only after executing the body.

Examples

Example 1: Basic Counting

#include <iostream>
using namespace std;

int main() {
    int count = 1;
    while (count <= 5) {
        cout << "Count: " << count << endl;
        count++;
    }
    cout << "Loop finished. Final count = " << count << endl;
    return 0;
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished. Final count = 6

The condition count <= 5 is checked before each pass. On the sixth check, count is 6, so 6 <= 5 is false and the loop exits. Notice the final printed value is 6, not 5 — the increment happens inside the body before the condition is re-tested, so the variable always ends up one past the last value that satisfied the condition.

Example 2: Summing Digits

#include <iostream>
using namespace std;

int main() {
    int number = 4826;
    int original = number;
    int sum = 0;

    while (number != 0) {
        int digit = number % 10;
        sum += digit;
        number /= 10;
    }

    cout << "Sum of digits of " << original << " is " << sum << endl;
    return 0;
}

Output:

Sum of digits of 4826 is 20

Here the loop’s condition is number != 0 — there’s no fixed number of iterations, which is exactly the situation while is designed for. Each pass peels off the last digit with % 10, adds it to sum, and then removes it with integer division / 10. Eventually number reaches 0 and the loop stops naturally.

Example 3: Compound Interest Simulation

#include <iostream>
using namespace std;

int main() {
    double balance = 1000.0;
    const double annualRate = 0.05;
    const double goal = 1500.0;
    int years = 0;

    while (balance < goal) {
        balance += balance * annualRate;
        years++;
    }

    cout << "It takes " << years << " years to reach the goal." << endl;
    cout << "Final balance: $" << balance << endl;
    return 0;
}

Output:

It takes 9 years to reach the goal.
Final balance: $1551.33

This is a realistic use case: we don’t know ahead of time how many years it will take, so a for loop with a fixed range doesn’t fit well. The while loop keeps compounding the balance by 5% each iteration and counting years until the balance meets or exceeds the goal, then stops automatically.

How It Works Step by Step

  • 1. The condition expression is evaluated.
  • 2. If it evaluates to false, the loop ends immediately and control passes to the code after the closing brace.
  • 3. If it evaluates to true, every statement in the body runs, in order, top to bottom.
  • 4. After the last statement in the body finishes, control jumps back to step 1 — the condition is evaluated again from scratch (it does not remember the previous result).
  • 5. This repeats until the condition is false, or the loop is exited early via break or return.

Common Mistakes

Mistake 1: Forgetting to update the loop variable, causing an infinite loop.

int i = 0;
while (i < 5) {
    cout << i << endl;
    // forgot i++ here
}

Since i never changes, i < 5 is true forever and the program hangs, printing 0 endlessly. Fix it by making sure something in the body moves the condition toward false:

int i = 0;
while (i < 5) {
    cout << i << endl;
    i++;
}

Mistake 2: Using assignment (=) instead of comparison (==) in the condition.

int flag = 0;
while (flag = 1) {   // always assigns 1, which is truthy -> infinite loop
    cout << "looping" << endl;
    break; // only saved by an explicit break here
}

flag = 1 is an assignment expression that evaluates to 1 (true) every time, so the condition can never naturally become false. Always double-check that a while condition uses ==, !=, <, >, or a plain boolean, not a single =.

Mistake 3: Off-by-one errors from using <= versus < incorrectly.

int i = 0;
int arr[5] = {10, 20, 30, 40, 50};
while (i <= 5) {           // bug: valid indices are 0..4
    cout << arr[i] << endl;
    i++;
}

This reads one element past the end of the array (undefined behavior). The fix is to use the correct bound:

int i = 0;
int arr[5] = {10, 20, 30, 40, 50};
while (i < 5) {
    cout << arr[i] << endl;
    i++;
}

Best Practices

  • Always initialize the loop-control variable before the loop starts — never rely on it having a “default” value.
  • Make sure at least one statement inside the body moves the condition toward becoming false.
  • Prefer a for loop when the number of iterations is known in advance; reserve while for cases where the stopping condition depends on runtime data (user input, sentinel values, convergence).
  • Use do-while only when the body genuinely must execute at least once before the condition is meaningful.
  • Keep the loop body short and readable; extract complex logic into a function if the body grows large.
  • Always use braces { } around the body, even for a single statement, to avoid accidental bugs when the code is later edited.
  • When looping based on user input, validate the input inside the loop so a malformed value can’t silently break the exit condition.

Practice Exercises

  • Exercise 1: Write a program that uses a while loop to print all even numbers from 2 to 20 (inclusive), each on its own line.
  • Exercise 2: Write a program that starts with the integer 1000 and repeatedly divides it by 2 (integer division) inside a while loop, counting how many divisions are needed until the value becomes 0. Print the count. (Expected result: 10 divisions.)
  • Exercise 3: Write a program that reverses the digits of the integer 1234 using a while loop (hint: repeatedly take the last digit with % 10 and build a new number). The expected output is 4321.

Summary

  • A while loop checks its condition before each iteration and can run zero times if the condition starts false.
  • A do-while loop checks its condition after the body, guaranteeing at least one execution.
  • Use while when the number of repetitions isn’t known ahead of time; use for when it is.
  • Every while loop needs an initialized variable, a meaningful condition, and code in the body that eventually makes the condition false — skipping any of these causes bugs or infinite loops.
  • Common bugs include forgetting to update the loop variable, confusing = with ==, and off-by-one boundary mistakes.