Beginner 10 min

While Loops

Master repetition in C++ with while loops and learn to avoid infinite loops

Learn how to repeat code execution with while loops and control program flow based on conditions.

A Simple Example

#include <iostream>

int main() {
    // Count from 1 to 5
    int count{1};

    while (count <= 5) {
        std::cout << "Count: " << count << "\n";
        count++;  // Increment count each time
    }

    std::cout << "Done!" << "\n";

    return 0;
}

Breaking It Down

How While Loops Work

  • Structure: while (condition) { code to repeat }
  • Checks condition before each iteration - if true, executes the loop body
  • If condition is false from the start, the loop never runs
  • Remember: The condition is re-evaluated before every iteration

Loop Control Variable

  • Must be initialized before the loop starts
  • Must be modified inside the loop body to eventually make condition false
  • Forgetting to modify it causes an infinite loop
  • Remember: count++ is shorthand for count = count + 1

Condition Evaluation

  • The condition can be any boolean expression
  • Common comparisons: <, <=, >, >=, ==, !=
  • Can combine conditions with && (and) or || (or)
  • Remember: The loop runs as long as condition is true

When to Use While Loops

  • Perfect when you do not know the exact number of iterations in advance
  • Reading user input until valid
  • Processing data until a sentinel value is encountered
  • Game loops that run until game over

Why This Matters

  • Imagine writing code to process 1000 user records, or waiting for valid input, or creating a game loop. Without loops, you would need to copy-paste the same code thousands of times.
  • Loops let you write code once and repeat it as many times as needed. They are essential for processing collections, handling user input, and building interactive programs.

Critical Insight

While loops are perfect when you do not know ahead of time how many iterations you will need. Use them for reading user input until valid, processing data until a sentinel value, game loops that run until game over, or waiting for a condition to be met.

If you know exactly how many times to loop (like "do this 10 times"), you will want a for loop instead (tomorrow's lesson).

Best Practices

Always initialize loop variables: Declare and initialize the loop control variable before the loop starts.

Ensure loop terminates: Always modify the loop variable inside the loop body so the condition eventually becomes false.

Use meaningful variable names: Use descriptive names like count, index, or attempts instead of single letters.

Keep loop bodies simple: If the loop body becomes too complex, consider extracting logic into separate functions.

Common Mistakes

Infinite loops: Forgetting to modify the loop variable causes the condition to never become false, creating an infinite loop.

Off-by-one errors: Using the wrong comparison operator (< vs <=) can cause the loop to run one too many or too few times.

Uninitialized variables: Forgetting to initialize the loop control variable before the loop leads to unpredictable behavior.

Modifying wrong variable: Updating a different variable inside the loop instead of the loop control variable.

Debug Challenge

This while loop has a bug that causes an infinite loop. Click the highlighted line to fix it:

1 #include <iostream>
2
3 int main() {
4 int count{1};
5 while (count <= 5) {
6 std::cout << count << "\n";
7 }
8 return 0;
9 }

Quick Quiz

  1. How many times does this loop run?
int x{5};
while (x > 0) {
    std::cout << x;
    x--;
}
5 times
4 times
6 times
  1. What happens with this code?
int n{10};
while (n < 5) {
    std::cout << n++;
}
Does not print anything
Prints 10 through 14
Infinite loop
  1. What is the final value of sum?
int sum{0};
int i{1};
while (i <= 3) {
    sum += i;
    i++;
}
6
3
7

Practice Playground

Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.

Lesson Progress

  • Fix This Code
  • Quick Quiz
  • Practice Playground - run once