C++C++ · Lesson 3 of 9

Control Flow

Same as C, with a few quality-of-life improvements. The range-based for loop alone is worth learning C++.

C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    // if/else — same as C, but condition can initialize
    int score = 85;
    if (score >= 90) cout << "A
";
    else if (score >= 80) cout << "B
";
    else if (score >= 70) cout << "C
";
    else cout << "Lower
";

    // C++17: if with initializer
    if (int n = score / 10; n >= 9) {
        cout << "Excellent
";
    } else {
        cout << "Grade: " << n << "
";
    }

    // Range-based for — iterate without index
    vector<int> numbers = {1, 2, 3, 4, 5};
    for (int n : numbers) {
        cout << n << " ";
    }
    cout << "
";

    // Classic for — when you need the index
    for (size_t i = 0; i < numbers.size(); i++) {
        cout << "numbers[" << i << "] = " << numbers[i] << "
";
    }

    // While
    int countdown = 5;
    while (countdown > 0) {
        cout << countdown-- << " ";
    }
    cout << "
";

    // Switch with strings (C++17 — actually, C++ switch doesn't work on strings)
    // Use if/else for string comparison
    string day = "Monday";
    if (day == "Saturday" || day == "Sunday") {
        cout << "Weekend!
";
    } else {
        cout << "Weekday.
";
    }

    return 0;
}