$ ./countdown32lastGo!1#include <iostream>2int main() {3 int n = 3;4 while (n > 0) {5 if (n == 1)6 std::cout << "last\n";7 else8 std::cout << n << "\n";9 n = n - 1;10 }11 std::cout << "Go!\n";12}int n??
Violet card: the program; the violet arrow marks the line running nowBlue cell: the variable n; rose block: the condition, true or falseTokens: n's value going to a test, a new value going into n, output going to the terminalOn the left: the program countdown.cpp, with an arrow beside the line that runs now. On the right: the variable n, the condition block and the terminal. The while loop tests n > 0 before every pass; inside it, if/else picks one of two lines to print; line 9 makes n smaller. The arrow jumps back from the loop's } to the test until the test is false. The output is 3, 2, last and Go!. The same countdown can be written as a for loop, which keeps the start, the test and the step on one line: for (int n = 3; n > 0; n = n - 1) { ... }. C++ also has do-while, switch, break and continue.

One line after another

  1. Control flow is the order in which lines run. Inside main, statements run one at a time, from the top down. Line 3 runs first: int n = 3; makes a variable n that holds 3.

Choosing a path

Repeating

What happens

;; step 1/9 · sequence
main() runs its statements in order, top to bottom
the arrow beside the card marks the line running now
line 3   int n = 3;   →  n holds 3
control flow = the order the lines run in
if and while change that order (next steps)

An if or else without braces controls only the one statement after it, as on lines 6 and 8. Many style guides suggest always writing braces { } so that adding a second line later cannot slip outside the if. Reaching the closing } of main without a return statement is the same as return 0;, so this program ends with exit status 0 (success). This rule applies only to main.