Part 3: Control flow

So far every program has run each line once, top to bottom. This part makes programs choose — run one block or another depending on a condition — and repeat — run a block again and again until the job is done. With these two abilities and the operators of Part 2, you can write real little programs: the part ends with the first checkpoint projects.

What you will learn

  • Choosing with if, else and else if chains, and why the order of a chain matters.
  • Choosing a value inside an expression with the conditional ? :.
  • Repeating with while, do-while and loop, and where each one tests its condition.
  • Leaving a loop early with break and skipping a pass with continue, including from nested loops with labels.
  • Describing a run of numbers with ranges .. and ..=, and walking one with for.
  • Selecting a branch by value with match, and using match as an expression that produces a value.

Choosing and repeating

flowchart LR
    cf(["Control flow"]) --> choose["Choose"]
    cf --> repeat["Repeat"]
    choose --> by_cond["by condition<br/>if · else if · ? :"]
    choose --> by_value["by value<br/>match · match expression"]
    repeat --> by_test["while a condition holds<br/>while · do-while · loop"]
    repeat --> by_range["over a range<br/>.. · ..= · for"]
    by_test --> jump["leave or skip<br/>break · continue · labels"]
    by_range --> jump

Lessons

LessonWhat you will learn
3.1Ifrun code only when a condition holds, with if and else
3.2Else ifchoose one of several branches with an else if chain
3.3Ternarypick one of two values inside an expression with ? :
3.4Whilerepeat while a condition holds — possibly zero times
3.5Do-whilerun the body first and test afterwards, so it runs at least once
3.6Looprepeat forever with loop until a break leaves
3.7Breakleave a loop early when the answer is found
3.8Continueskip the rest of one iteration and carry on with the next
3.9Rangedescribe a run of numbers with .. and ..=
3.10Forwalk a range with for
3.11Labelname a loop, so break can leave an outer one
3.12Matchselect a branch by value with match, and default with else
3.13Match expressionuse match as a value, not only as a statement

Before you start

Finish Part 1: Basics and Part 2: Operators first — every condition in this part is a comparison or a logical expression from Part 2. Each lesson's package is in the Examples repository's ControlFlow/ folder:

cd Examples/ControlFlow/If
rux run

After this part

You are ready for the first checkpoint projects: Thanks, which prints a banner using loops and match expressions, and FizzBuzz, the classic test of getting an else if chain in the right order. Then Part 4: Functions gives a piece of work a name, so you can reuse it instead of repeating it.

For the full rules behind this part, see Statements — if, match, while, for, loop and break / continue — and Ranges in the Rux Reference.