Control Flow and Functions

Control Flow and Functions

Use `if`, loops, and reusable functions to organize program behavior.

Control Flow and Functions

Branching with if

if (temperature > 30) {
    std::cout << "Hot\n";
} else {
    std::cout << "Not hot\n";
}

Repetition with loops

for (int i = 1; i <= 5; ++i) {
    std::cout << i << '\n';
}

Extracting a function

int square(int x) {
    return x * x;
}

Combined example

#include <iostream>

bool is_even(int value) {
    return value % 2 == 0;
}

int main() {
    for (int i = 1; i <= 10; ++i) {
        if (is_even(i)) {
            std::cout << i << " is even\n";
        }
    }
}

Key lessons

switch and enum class

enum class MenuChoice { add, remove, quit };

void handle(MenuChoice choice) {
    switch (choice) {
    case MenuChoice::add:
        add_item();
        break;
    case MenuChoice::remove:
        remove_item();
        break;
    case MenuChoice::quit:
        shutdown();
        break;
    }
}

This keeps control flow readable when the set of cases is closed and explicit.

Choosing parameter styles

Practice extension

Refactor a loop-heavy program into three functions: input, computation, and output. The goal is to make main() read like a summary of the program.