Section 4

Control structures

Repeating, traversing, choosing among many — everything that decides the order of statements.

The previous section gave the program a choice between two paths. It still cannot do a thing several times — and until it can, every repetition has to be written out by hand.

This section gathers what commands the order of execution: repeating while a condition holds, counting, traversing a sequence of values, and choosing among several cases at once.

In this section

  • 4.1While loop

    while, do/while, and the one thing that keeps a loop from running forever.

  • 4.2For loop

    The three clauses of for, the scope of its variable, and the two words that cut it short.

  • 4.3For in loop

    A sequence of values, and the loop that takes them one at a time, with no index or counter.

  • 4.4Switch case

    One value, some cases, a default — and what it works on.