100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

while Loop in C++

Understand the C++ `while` loop, how its entry condition is tested before every iteration, and when to use it over a `for` loop.

LoopsBeginner5 min readJul 7, 2026
Analogies

1. Intro

The while loop is C++'s simplest looping construct: it repeats a block of code as long as a given condition remains true. Unlike the for loop, it does not bundle initialization or update logic into its header, making it the natural choice when the number of iterations is not known ahead of time — such as reading input until a sentinel value appears.

🏏

Cricket analogy: A while loop bowling 'until the batsman is out' mirrors a bowler continuing to bowl overs without a fixed pre-set count - unlike a for loop's fixed 20-over T20 limit, the innings continues until a specific condition (a wicket) ends it.

2. Syntax

cpp
while (condition) {
    // loop body
}

3. Explanation

Before every iteration, the while loop evaluates condition. If it is true, the body executes and then control jumps back to re-check the condition. If it is false, the loop terminates and execution continues after the closing brace. Because the check happens *before* the body runs, a while loop is an entry-controlled loop and can execute zero times if the condition is false from the start. You must ensure something inside the body eventually makes the condition false (such as incrementing a counter or reading new input) — otherwise the loop becomes infinite.

🏏

Cricket analogy: A while loop is entry-controlled like a bowler checking with the umpire before every single delivery whether overs remain - if the quota's already used, that over never even starts, and someone must actually bowl (update the counter) or the innings never ends.

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    int i = 1;
    while (i <= 5) {
        cout << "Value: " << i << endl;
        i++;
    }
    return 0;
}

5. Output

text
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5

6. Key Takeaways

  • A while loop checks its condition before each iteration, making it entry-controlled.
  • The loop body can execute zero times if the condition starts out false.
  • The counter or state variable must be declared and updated manually, unlike in a for loop.
  • Best suited for loops with an unknown or condition-driven number of iterations.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#WhileLoopInC#While#Loop#Syntax#Explanation#Loops#StudyNotes#SkillVeris