AnyCompiler

Control Flow

if/else works as you'd expect from any C-family language — a condition in parentheses, followed by a block.

#include <iostream>
using namespace std;

int main() {
    int number = 7;
    if (number % 2 == 0) {
        cout << number << " is even" << endl;
    } else {
        cout << number << " is odd" << endl;
    }
    return 0;
}
Output
7 is odd

for and while

A classic for loop declares an index, a condition, and an increment all in its header. while just repeats as long as its condition holds, with no built-in index at all.

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 3; i++) {
        cout << "i = " << i << endl;
    }

    int count = 0;
    while (count < 3) {
        cout << "count = " << count << endl;
        count++;
    }
    return 0;
}
Output
i = 0
i = 1
i = 2
count = 0
count = 1
count = 2

switch

switch compares a value against a series of constant cases, falling through to the next case unless you break. default catches anything not matched above it.

#include <iostream>
using namespace std;

int main() {
    int day = 3;
    switch (day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        default:
            cout << "Unknown" << endl;
    }
    return 0;
}
Output
Wednesday

Next: arrays and vectors — C++'s fixed-size arrays versus the STL's growable std::vector.

Practice exercise

Set a variable score: int = 73. Use a ternary expression to set a variable grade to "pass" if score is 60 or above, otherwise "fail", then print grade.