Home Tutorials C++ Tutorial While Loop
While Loop

While Loop


C++ While Loop

Definition: The while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. It is known as an "entry-controlled" loop because the condition is evaluated before the code inside the loop body is executed.

Why: In any standard C++ curriculum, while loops are a fundamental building block. They are essential for tasks where you don't necessarily know in advance how many times an action needs to repeat—such as reading data until the end of a file or waiting for a specific user input.


Syntax and Logic

The loop repeatedly checks the condition in parentheses. As long as the condition remains true, the code inside the curly braces will run. Once the condition becomes false, the program skips the loop and continues with the next line of code.

Example: Counting to Five

In this example, the program uses a counter variable i to print numbers from 1 to 5. The loop continues as long as i is less than or equal to 5:

#include <iostream>
using namespace std;

int main() {
    int i = 1; // Initialization

    while (i <= 5) { // Condition
        cout << i << endl;
        i++; // Increment (Updates the condition)
    }

    return 0;
}

The Three Essentials of a Loop

For a loop to function correctly and avoid errors, it must manage these three stages:

Stage Purpose
Initialization Setting the starting value of a counter or flag (e.g., int i = 1;).
Condition The "gatekeeper" that decides if the loop should run another time.
Update Changing the variable inside the loop (e.g., i++) so that the condition eventually becomes false.

Key Notes

  • Infinite Loops: If the condition never becomes false (for example, if you forget to include i++), the loop will run forever. This will cause your program to "freeze" or crash.
  • Zero-Iteration: Because the condition is checked first, if it is false at the very beginning (e.g., if i = 10), the code inside the loop will never execute at all.
  • While vs. For: While loops are generally preferred when the number of iterations is unknown. For loops are preferred when you have a specific range or number of times you want to repeat.
  • User Input: A common use for while loops is "input validation"—repeatedly asking a user for a number until they enter one that is within a valid range.

🏋️ Test Yourself With Exercises

Take our quiz on While Loop to test your knowledge.

Browse Quizzes »