Concepts / Learning C++

Learning C++

You do not need to know every detail of C++ to write good programs; focus on programming techniques rather than language features.

  • Programming
Interactive lab

Try it: while Loops, break and continue

How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.

How it works

  1. Evaluate the condition. If it is False, skip the body and continue after the loop.
  2. If it is True, run the body from the top, then go back and evaluate the condition again.
  3. continue skips the rest of the body and goes straight back to the condition check.
  4. break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
  5. If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.

Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.

Educational simulation

Loading the simulation…

The Worry Before the First Loop

Many learners reach the point of writing a repeating program with a quiet worry. They feel they must first master every corner of the language before they are allowed to write anything that repeats. A loop starts to look like a trap for people who have not yet memorized each rule, so they hesitate.

This article tests that belief rather than accepting it. Before reading each explanation, make a prediction about the program you are about to see. Ask yourself what happens first, what happens next, and where you expect the repetition to stop. Writing down a guess, even a wrong one, makes the correction that follows far more useful.

What do you think happens?

Before you read further: how many times do you think the loop below prints a line, and what is the final line printed?

  • Three lines of numbers, then done

  • Two lines of numbers, then done

  • Infinitely many lines

Reveal answer
Answer:

Three lines of numbers, then done

The counter starts at 0 and the condition count < 3 is checked before each pass. It is true for 0, 1, and 2, so the body prints three numbers. When count reaches 3 the condition becomes false and the loop ends, so the next statement prints done.

Techniques Before Language Details

The more useful habit is to focus on programming techniques rather than on language features. A technique is a way of solving a problem, such as repeating an action until a goal is met. A language feature is a specific keyword or rule. A while loop is a feature, but the technique it supports, doing something repeatedly while a condition holds, applies in every program you will write.

This is why you can start writing loops before you know everything. Learn the technique first, then look up the finer details of the language as they become relevant to your program.

How a while Loop Checks Its Condition

A while loop repeats a block of statements. Each time around, the program first evaluates a condition. If the condition is true, the body runs once and control returns to the condition. If the condition is false, the body is skipped and execution continues with the statement that follows the loop. Repetition therefore depends entirely on the condition being checked again on every pass.

Check conditionevaluated before each passRun loop bodyruns only when trueNext statement afterloopreached when falsetruecheck againfalse
In what order do the condition check, the loop body, and the exit happen on each pass, and at which point does the loop stop?

Read the diagram as a cycle with one exit. The condition is always the first thing checked on each pass, the body only runs on a true result, and the only way out is the false branch. Notice that the body never runs on its own; it always returns to the check.

Tracing a Counter Through Three Passes

Now watch the state change. The example below uses a counter variable named count. Trace what count holds before each check, then compare your trace with the output.

cpp
Output
0
1
2
done
Walk through it
  1. 1
    count starts at 0, so the check count < 3 is true and the body runs, printing 0
  2. 2
    The body sets count to 1; control returns to the check, which is true, so 1 is printed
  3. 3
    count becomes 2; the check is true, so 2 is printed
  4. 4
    count becomes 3; the check count < 3 is now false, the body is skipped, and the loop ends
  5. 5
    The statement after the loop runs and prints done
Notes on the code
  • count < 3 is the condition checked before each pass
  • The body prints the current count and then increases it
  • The increment is what eventually makes the condition false
Worked example

Tracing the Condition Value on Each Check

For the counter program above, what is the value of count and the result of the condition at each check, and how many times does the body run?

  1. 1
    Check 1

    count is 0. 0 < 3 is true, so the body runs and prints 0.

  2. 2
    Check 2

    count is 1 after the body. 1 < 3 is true, so the body runs and prints 1.

  3. 3
    Check 3

    count is 2. 2 < 3 is true, so the body runs and prints 2.

  4. 4
    Check 4

    count is 3. 3 < 3 is false, so the body is skipped and the loop stops.

Result

The check is evaluated four times, the body runs three times, and the program then continues with the statement after the loop.

Why the Body Must Change the Condition

Notice what the diagram does not show: the body itself is responsible for moving the program toward an end. The loop never adjusts the condition on its own. If nothing inside the body changes the values the condition depends on, the condition stays true forever. This is the central point to hold onto when reasoning about any loop.

Leaving a switch Early with break

Sometimes a program should not wait for the normal stopping point. A switch selects one case based on a value. A switch can exit a case by returning from the function that contains it, but that is not always what we want. Often we only want execution to continue with the statement that follows the switch. A break statement does exactly that: it exits the switch and continues with the statement after it, without needing to return from the function.

The source illustrates this with a parser for a trivial command video game. Each command selects a case in a switch, and a break ends that case so the function can carry on with the statements after the switch rather than leaving the whole function. The example below follows that same pattern in a smaller form.

cpp
Output
south
waiting
Walk through it
  1. 1
    command is 2, so execution jumps to case 2
  2. 2
    The statement prints south
  3. 3
    break exits the switch immediately; cases 1 and 3 are not run
  4. 4
    Execution continues with the statement after the switch, which prints waiting
Notes on the code
  • command selects the case whose label matches its value
  • The break at the end of case 2 exits the switch
  • The line after the switch still runs because the function is not exited
command is 2value selects a casecase 2 bodyprints southbreakexits the switchStatement afterswitchprints waitingcase 1 and case 3skippedmatchesreachesjumps tobypasses
After a break runs inside a switch case, which line does execution jump to next, and which case lines are skipped?

The diagram shows the single route that matters. The matching case runs, the break sends control out of the switch, and the cases that do not match are never touched. Execution then resumes at the statement after the switch, which is why waiting appears in the output.

What Happens Without a break

The break is what stops the matching case from running into the next one. When a case has no break, execution does not stop at the end of that case; it carries on into the following case body. The diagram below changes only one thing from the previous example: the break after case 2 has been removed.

case 2 matchesentry pointprint southcase 2 bodyprint eastcase 3 body runs toobreakexits the switchentersno break, falls throughreaches
If a case has no break, which subsequent case bodies run, and in what order?

With the break removed, the same value 2 prints south and then east, because execution flows from case 2 into case 3 before anything exits the switch. The line waiting still prints afterward. The lesson is that a break is an explicit instruction to leave the switch, and its absence changes where control goes next.

Mistakes Beginners Make with Loops and Switches

  • Common mistake

    Refusing to write any loop until every language rule is memorized

    Why it fails

    A loop is a technique that applies across programs. Its core behavior, checking a condition and repeating while it holds, can be learned directly, and finer details can be looked up when they become relevant.

    Do this instead

    Start with the technique: write a small loop, trace it, and consult the ISO C++ standard only when a precise definition matters.

  • Common mistake

    Writing a while loop whose body never changes the condition

    What it looks like
    while (count < 3) { std::cout << count << std::endl; } with no increment
    Why it fails

    The condition is checked again on every pass, so if nothing in the body changes its values, it stays true and the loop never stops.

    Do this instead

    Identify the statement in the body that moves the condition toward false, such as count = count + 1.

  • Common mistake

    Expecting break to return from the whole function

    Why it fails

    A break inside a switch exits only the switch. The statement after the switch still runs.

    Do this instead

    If you want to leave the function, use a return. Use break when you only want to continue with the statement after the switch.

  • Common mistake

    Forgetting the break at the end of a case

    What it looks like

    case 2: prints south, with no break, followed by case 3

    Why it fails

    Without a break, execution continues into the next case body.

    Do this instead

    End each case that should stand alone with a break, or deliberately use fallthrough when you intend it.

Practice Tracing Control Flow

MEDIUM

Trace the following program by hand before checking anything. Write down the value of total and the output after each pass, then state the final output. Remember that the condition is checked before each pass. Program: int total = 1; while (total < 10) { std::cout << total << std::endl; total = total * 2; } std::cout << "end" << std::endl;

Hints
  • Check the condition before the first pass; total starts at 1, and 1 < 10 is true.
  • Multiply total by 2 on each pass and watch which value first fails the check.
  • The statement after the loop runs only once the condition is false.
EASY

Predict the output of this switch with value 3 and no break after case 2. Then state which line runs last. switch (value) { case 2: std::cout << "two" << std::endl; case 3: std::cout << "three" << std::endl; break; case 4: std::cout << "four" << std::endl; break; } std::cout << "after" << std::endl;

Hints
  • The value 3 selects case 3, not case 2, so consider whether case 2 runs at all.
  • The break belongs to case 3 and exits the switch.

Key Takeaways

  • You do not need to know every detail of C++ to write useful programs; learn the programming technique first and look up language details as they become relevant.
  • A while loop checks its condition before each pass, runs the body while the condition is true, and continues with the next statement once the condition is false.
  • The body must change the values the condition depends on, or the loop may never stop.
  • A break inside a switch exits the switch and continues with the statement after it, without returning from the function.
  • Without a break, a case body runs into the following case body, so the break is what controls where execution goes next.

Related concepts

More concepts starting with L