Skip to content
C++
Language
since C++11
Beginner

Control the Flow of Your C++ Programs

Learn to use if/else, loops, and switch to make your C++ programs make decisions and repeat work automatically.

By the end of this page, you will be able to write programs that branch based on conditions using if/else, repeat work using for and while loops, choose between many cases using switch, and avoid the most common mistakes beginners make with control flow.

What and Why

Every useful program makes decisions. A thermostat turns the heater on if the room is cold. A download manager retries while the connection is unstable. A music player skips to the next track when the current one ends.

In C++, control flow is the set of statements that tell the CPU which instructions to execute next, and how many times. Without it, your program is just a straight line β€” it runs every statement once, top to bottom, and exits. Control flow lets you build programs that react, repeat, and choose.

C++11 is the baseline standard for this page. Everything here compiles with -std=c++11 or newer.


Step by Step

Branching with if and else

The simplest decision: run one block of code if a condition is true, and a different block if it is false.

cpp
#include <iostream>

int main() {
    int temperature = 18;

    if (temperature < 20) {
        std::cout << "It's cold β€” wear a jacket.\n";
    } else {
        std::cout << "Nice weather!\n";
    }

    return 0;
}

The condition inside if (...) must evaluate to a boolean β€” true or false. Any non-zero integer counts as true; zero counts as false.

You can chain more conditions with else if:

cpp
#include <iostream>

int main() {
    int score = 74;

    if (score >= 90) {
        std::cout << "Grade: A\n";
    } else if (score >= 80) {
        std::cout << "Grade: B\n";
    } else if (score >= 70) {
        std::cout << "Grade: C\n";
    } else {
        std::cout << "Grade: F\n";
    }

    return 0;
}

C++ evaluates the conditions top to bottom and runs the first block whose condition is true. The rest are skipped.


Repeating work with for

A for loop runs a block of code a specific number of times.

cpp
#include <iostream>

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << "Count: " << i << "\n";
    }

    return 0;
}

The three parts inside for(...) are:

PartWhat it does
int i = 0Initialise a counter before the first iteration
i < 5Check this before each iteration; stop when false
i++Run this after each iteration (increment the counter)

C++11 added a range-based for, which is cleaner when you want to visit every element in a collection:

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores = {88, 95, 72, 61};

    for (int s : scores) {
        std::cout << "Score: " << s << "\n";
    }

    return 0;
}

Read for (int s : scores) as "for each int s in scores". No index arithmetic needed.


Repeating while a condition holds: while

Use while when you do not know in advance how many times you need to loop.

cpp
#include <iostream>

int main() {
    int n = 1;

    while (n <= 100) {
        n *= 2;
    }

    std::cout << "First power of 2 above 100: " << n << "\n";
    return 0;
}

The loop body runs as long as the condition is true. If the condition is false the very first time, the body never runs at all.

A do/while loop guarantees the body runs at least once β€” the condition is checked at the end:

cpp
#include <iostream>

int main() {
    int guess;

    do {
        std::cout << "Guess a number (1–10): ";
        std::cin >> guess;
    } while (guess < 1 || guess > 10);

    std::cout << "Valid input received.\n";
    return 0;
}

Choosing between many cases: switch

When you have one integer or character value and many possible outcomes, switch is cleaner than a chain of else if.

cpp
#include <iostream>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        default:
            std::cout << "Another day\n";
            break;
    }

    return 0;
}

The break at the end of each case is required β€” without it, execution falls through to the next case (more on this below).


Common Patterns

Early exit with break and continue

break exits the nearest enclosing loop immediately. continue skips the rest of the current iteration and goes straight to the next check.

cpp
#include <iostream>

int main() {
    for (int i = 0; i < 20; i++) {
        if (i % 2 == 0) continue;   // skip even numbers
        if (i > 10)    break;       // stop after 10

        std::cout << i << " ";
    }
    std::cout << "\n";
    // Output: 1 3 5 7 9
    return 0;
}

Searching a collection

cpp
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> names = {"Alice", "Bob", "Carol", "Dave"};
    std::string target = "Carol";
    bool found = false;

    for (const std::string& name : names) {
        if (name == target) {
            found = true;
            break;
        }
    }

    if (found) {
        std::cout << target << " is in the list.\n";
    } else {
        std::cout << target << " was not found.\n";
    }

    return 0;
}

Accumulating a result

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> prices = {12, 7, 34, 5, 19};
    int total = 0;

    for (int p : prices) {
        total += p;
    }

    std::cout << "Total: " << total << "\n";
    return 0;
}

What Can Go Wrong

Forgetting break in a switch

cpp
// BUG: falls through from case 1 into case 2
switch (x) {
    case 1:
        std::cout << "One\n";
        // missing break!
    case 2:
        std::cout << "Two\n";
        break;
}
// If x == 1, prints both "One" and "Two".

Always add break at the end of every case unless fall-through is intentional and clearly commented.

Using = instead of == inside if

cpp
int x = 5;
if (x = 10) {          // BUG: assigns 10 to x, always true
    std::cout << "x is 10\n";
}

= assigns; == compares. The compiler may warn about this β€” read your warnings. A defensive habit is to put the constant on the left: if (10 == x) β€” an accidental = then becomes a compile error.

Off-by-one errors in for loops

cpp
// Intends to print indices 1 through 5
for (int i = 1; i <= 5; i++) {   // correct: <=
    std::cout << i << " ";
}

// Common mistake: stops at 4
for (int i = 1; i < 5; i++) {    // wrong: < misses the last element
    std::cout << i << " ";
}

Read the condition carefully: < vs <= changes the last iteration.

Infinite loops

cpp
int i = 0;
while (i < 10) {
    std::cout << i << "\n";
    // BUG: forgot i++, loop never ends
}

If your program hangs, check that every loop variable gets updated and can eventually make the condition false.


Quick Reference

StatementUse when
if / else if / elseYou have a condition that is true or false
switchOne integer/char value, many fixed cases
for (init; cond; step)You know the iteration count in advance
for (T x : collection)You want every element of a range (C++11)
while (cond)Repeat while a condition holds; may run zero times
do { } while (cond)Like while, but body runs at least once
breakExit the current loop or switch immediately
continueSkip to the next loop iteration

What's Next

  • Variables and Types β€” understand the data that your conditions and loops operate on
  • Functions β€” package repeated logic into reusable blocks
  • C++11 Features β€” the full set of language improvements in the standard this page targets