🧱 Section 1 · Foundations 🟢 Beginner MODULE 03

Control Flow — if/else, switch, Loops

⏱️ 26 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Section 160%
🎯 What you'll learn: How to make your programs branch with if/else if/else and switch, how to repeat work with for, while, and do-while loops, how break and continue control loop execution, and how to combine a loop with a conditional in a real worked example — FizzBuzz.

if / else if / else

An if statement runs a block of code only when its condition evaluates to true. Chain additional checks with else if, and catch everything else with a final else.

grade.cpp — Branching with if/else if/else
C++
// grade.cpp
#include <iostream>

int main() {
    int score = 82;

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

    return 0;
}
💡
Only one branch runs
C++ checks each condition top to bottom and stops at the first one that's true — the rest are skipped entirely. With score = 82, the first check (>= 90) fails, the second (>= 80) succeeds, so "Grade: B" prints and nothing after it runs.

switch Statements

A switch compares one value against several possible case labels — a cleaner alternative to a long chain of else if checks when you're comparing the same variable against many exact values.

day_name.cpp — switch with break
C++
// day_name.cpp
#include <iostream>

int main() {
    int day = 3;

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

    return 0;
}
⚠️
Forgetting break causes fallthrough
Without a break, execution doesn't stop at the end of a matching case — it "falls through" and keeps running the code in the next case too, regardless of whether that case's value matches. This is honest C++ behavior, not a bug, but it's a very common source of accidental bugs when a break is missing.

Intentional fallthrough — grouping cases

Fallthrough isn't always a mistake — it's sometimes used on purpose to group multiple case values under one block of code, by stacking case labels with no code (and no break) between them:

weekday_check.cpp — Grouping Cases on Purpose
C++
// weekday_check.cpp
#include <iostream>

int main() {
    int day = 6;

    switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            std::cout << "Weekday" << std::endl;
            break;
        case 6:
        case 7:
            std::cout << "Weekend" << std::endl;
            break;
        default:
            std::cout << "Invalid day" << std::endl;
    }

    return 0;
}

With day = 6, execution jumps straight to case 6, falls through the empty case 7 label (no code there to run), hits the shared std::cout line, prints "Weekend", and the break stops it there.

for Loops

A for loop packs initialization, condition, and update into one line — ideal when you know roughly how many times you want to repeat something.

for_loop.cpp — Counting with a for Loop
C++
// for_loop.cpp
#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) {
        std::cout << "i = " << i << std::endl;
    }
    return 0;
}
1
int i = 1; — runs once
The initializer runs a single time, before the loop starts.
2
i <= 5; — checked every iteration
Before each pass through the body, the condition is checked. If it's false, the loop ends immediately.
3
i++ — runs after every iteration
After the body finishes, the update expression runs, then the condition is checked again.

while and do-while Loops

A while loop checks its condition before each iteration — if it's false from the start, the body never runs. A do-while loop checks its condition after each iteration, so the body always runs at least once.

while_loop.cpp — Counting Down
C++
// while_loop.cpp
#include <iostream>

int main() {
    int n = 5;
    while (n > 0) {
        std::cout << n << std::endl;
        n--;
    }
    return 0;
}
do_while.cpp — Body Always Runs Once
C++
// do_while.cpp
#include <iostream>

int main() {
    int n = 0;
    do {
        std::cout << "n = " << n << std::endl;
        n++;
    } while (n < 3);
    return 0;
}
When to reach for do-while
Use do-while when you need the body to execute at least once no matter what — a classic example is a menu prompt: you want to show the menu once before checking whether the user chose to exit.

break & continue

break exits the nearest enclosing loop (or switch) immediately. continue skips the rest of the current iteration and jumps straight to the next one, without exiting the loop.

break_continue.cpp — Skipping and Stopping
C++
// break_continue.cpp
#include <iostream>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 6) break;          // stop the loop entirely at i == 6
        if (i % 2 == 0) continue; // skip even numbers
        std::cout << i << std::endl;
    }
    return 0;
}

This prints 1, 3, 5 — even numbers are skipped by continue, and the loop stops entirely once i reaches 6 because of break.

Worked Example — FizzBuzz

FizzBuzz combines a loop with nested conditionals: for numbers 1 to 20, print "Fizz" if divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if divisible by both, and the number itself otherwise.

fizzbuzz.cpp — Loop + Conditional Together
C++
// fizzbuzz.cpp
#include <iostream>

int main() {
    for (int i = 1; i <= 20; i++) {
        if (i % 15 == 0) {
            std::cout << "FizzBuzz" << std::endl;
        } else if (i % 3 == 0) {
            std::cout << "Fizz" << std::endl;
        } else if (i % 5 == 0) {
            std::cout << "Buzz" << std::endl;
        } else {
            std::cout << i << std::endl;
        }
    }
    return 0;
}
💡
Why check divisible-by-15 first
A number divisible by both 3 and 5 is divisible by 15. Checking i % 15 == 0 before the individual 3 and 5 checks ensures "FizzBuzz" prints for those numbers instead of just "Fizz" — order matters in an if/else-if chain.

Lesson Summary

Let's recap everything you learned in this lesson:

if/else if/else runs the first matching branch and skips the rest.
switch compares one value against several cases — always add break unless you intentionally want fallthrough.
for loops pack init/condition/update in one line; while checks before each pass; do-while always runs the body at least once.
break exits a loop immediately; continue skips to the next iteration.
Real programs combine loops and conditionals together — like FizzBuzz — to process data one element at a time.
🧩 Knowledge Check — Lesson 3
Answer all 5 questions to test your understanding. Instant feedback on every answer.
1. Which keyword prevents a switch statement from falling through to the next case?
2. At minimum, how many times does a do { ... } while(cond); loop's body execute?
3. What does continue; do inside a loop?
4. In for (int i = 0; i < 5; i++), how many times does the loop body run?
5. What's the key difference between while and do-while?
💪
Coding Challenge — Lesson 3
Apply what you learned · Beginner Level

Now it's your turn to write real code. Compile and run it with g++ or an online compiler.

Challenge: Print All Even Numbers 1–50 🔢

Write a program called evens.cpp that prints every even number from 1 to 50 (inclusive), one per line. Your output should start:

2
4
6
...
50

Rules: Use a for loop and the % operator to check for even numbers. Do not hard-code the list — the loop must generate it.
💡 Show hints if you're stuck
  • Loop with for (int i = 1; i <= 50; i++)
  • Inside the loop, check if (i % 2 == 0)
  • If true, print i with std::cout << i << std::endl;
  • Bonus: try rewriting it starting the loop at i = 2 and stepping by i += 2 instead — no if-check needed
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 3 Complete!

Your programs can now branch and repeat. Next up: organizing code into reusable functions.

Module 03 of 26 Section 1 — C++ Foundations