Skip to main content

C++ While Loop – Syntax, Examples & Common Mistakes

Loops are one of the first real "superpowers" you get as a programmer — instead of writing the same line of code ten times, you write it once and let it repeat. In C++, the while loop is the simplest of the three loop types, and it's the one you reach for when you don't know in advance how many times something needs to run.

This guide covers everything you need: the syntax, how it actually executes step by step, real examples, the mistakes beginners make most often, and how it compares to do...while and for loops.


What Is a While Loop in C++?

A while loop repeatedly executes a block of code as long as a condition stays true. Think of it as telling the computer: "Keep doing this until I say stop."

while (condition) {
    // code to execute
}

Here's what happens on every pass:

  1. C++ checks the condition.
  2. If it's true, the code inside the { } runs.
  3. Once the block finishes, C++ jumps back and checks the condition again.
  4. This repeats until the condition becomes false, at which point the loop stops and the program moves on.

Because the condition is checked before the loop body runs, a while loop is called an entry-controlled loop — if the condition is false the very first time, the body never executes at all.


A Simple First Example

#include <iostream>
using namespace std;

int main() {
    int num = 1;

    while (num <= 5) {
        cout << num << endl;
        num++;
    }

    return 0;
}

Output:

1
2
3
4
5

Walking through it:

  • num starts at 1.
  • C++ checks num <= 5 before every iteration.
  • Each time through, the loop prints num, then num++ increases it by 1.
  • Once num becomes 6, the condition is false, and the loop exits.

Key Characteristics of a While Loop

Feature What it means
Pre-check condition The condition is tested before each iteration — the body might not run at all.
Indefinite iterations You don't need to know the exact number of repetitions in advance.
Manual update required You must change the condition variable yourself inside the loop, or it never ends.

That last point is the source of almost every while-loop bug, so let's cover it properly.


Common Mistakes to Avoid

1. Forgetting to Update the Condition (Infinite Loop)

int num = 1;
while (num <= 5) {
    cout << num << endl; // num never changes — this runs forever
}

If nothing inside the loop changes the value being tested, the condition stays true forever and the program hangs. Always make sure something in the loop body moves you toward the exit condition (num++, reading new input, etc.).

2. Off-by-One Errors

Mixing up < and <= is a classic bug:

while (i < 5)   // runs for i = 0,1,2,3,4  → 5 iterations
while (i <= 5)  // runs for i = 0,1,2,3,4,5 → 6 iterations

Be deliberate about which one you actually want.

3. Using an Unrelated or Mismatched Condition

Make sure the condition you're testing actually reflects what you're trying to accomplish. A condition that's technically valid C++ but logically disconnected from the task will produce a loop that runs the "wrong" number of times without ever crashing — which makes it harder to spot.


Practical Examples

Example: Validating User Input

#include <iostream>
using namespace std;

int main() {
    int age;

    cout << "Enter your age (1-100): ";
    cin >> age;

    while (age < 1 || age > 100) {
        cout << "Invalid input. Try again: ";
        cin >> age;
    }

    cout << "Thank you! Your age is " << age << "." << endl;
    return 0;
}

This keeps asking until the user enters a valid number — a textbook use case for while, since you have no idea how many bad attempts the user will make.

Example: Running Total

#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;

    cout << "Enter numbers to add (0 to stop): ";

    while (true) {
        cin >> num;
        if (num == 0) break; // exits the loop
        sum += num;
    }

    cout << "Total sum is " << sum << "." << endl;
    return 0;
}

Example: Simple Password Check

#include <iostream>
#include <string>
using namespace std;

int main() {
    string password;

    while (password != "letmein") {
        cout << "Enter password: ";
        cin >> password;

        if (password != "letmein") {
            cout << "Wrong password. Try again." << endl;
        }
    }

    cout << "Access granted!" << endl;
    return 0;
}

Example: Countdown Timer

#include <iostream>
#include <unistd.h> // for sleep()
using namespace std;

int main() {
    int countdown = 10;

    while (countdown > 0) {
        cout << "Countdown: " << countdown << " seconds remaining..." << endl;
        sleep(1);
        countdown--;
    }

    cout << "Time's up!" << endl;
    return 0;
}

Controlling a While Loop: break and continue

Two keywords give you finer control over a running loop:

  • break exits the loop immediately, skipping any remaining iterations.
  • continue skips the rest of the current iteration and jumps straight to the next condition check.
#include <iostream>
using namespace std;

int main() {
    int i = 0;

    while (i < 10) {
        i++;
        if (i == 5) continue; // skip printing 5
        if (i == 8) break;    // stop the loop entirely at 8
        cout << i << endl;
    }

    return 0;
}

Output: 1 2 3 4 6 7


Nested While Loops

A while loop can contain another while loop — useful for grids, tables, or comparing pairs of values.

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    while (i <= 3) {
        int j = 1;
        while (j <= 3) {
            cout << "i=" << i << " j=" << j << "  ";
            j++;
        }
        cout << endl;
        i++;
    }

    return 0;
}

Each inner loop fully completes before the outer loop moves to its next iteration — this is what produces a grid-like output.


while vs do...while: What's the Difference?

C++ has a close cousin of while called do...while. The difference is when the condition is checked:

while do...while
Condition checked Before the body runs After the body runs
Minimum executions 0 (may never run) Always at least 1
Syntax while (cond) { } do { } while (cond);
int num = 10;

// while: body never runs, since condition is false immediately
while (num < 5) {
    cout << num << endl;
}

// do...while: body runs once regardless, THEN checks condition
do {
    cout << num << endl;
} while (num < 5);

Use do...while when you need the code to run at least once no matter what — a common example is displaying a menu before checking if the user wants to exit.


while vs for: Which Should You Use?

Both loop indefinitely based on a condition, but they suit different situations:

  • Use for when you know the number of iterations ahead of time (looping through an array of fixed size, counting 1 to 10).
  • Use while when the number of iterations depends on something that isn't known in advance — user input, a network response, a sensor reading, or any condition that could go either way.
// for: exact number of iterations known
for (int i = 0; i < 10; i++) { /* ... */ }

// while: unknown number of iterations
while (cin >> value) { /* keep reading until input stops */ }

When to Choose a While Loop

Reach for a while loop when:

  1. You don't know the exact number of iterations upfront.
  2. The loop needs to break based on a dynamic condition (user input, external data, a sensor, etc.).
  3. You want the flexibility to check any custom condition, not just a counter.

Popular posts from this blog

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...