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,elseandelse ifchains, and why the order of a chain matters. - Choosing a value inside an expression with the conditional
? :. - Repeating with
while,do-whileandloop, and where each one tests its condition. - Leaving a loop early with
breakand skipping a pass withcontinue, including from nested loops with labels. - Describing a run of numbers with ranges
..and..=, and walking one withfor. - Selecting a branch by value with
match, and usingmatchas 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 --> jumpLessons
| Lesson | What you will learn | |
|---|---|---|
| 3.1 | If | run code only when a condition holds, with if and else |
| 3.2 | Else if | choose one of several branches with an else if chain |
| 3.3 | Ternary | pick one of two values inside an expression with ? : |
| 3.4 | While | repeat while a condition holds — possibly zero times |
| 3.5 | Do-while | run the body first and test afterwards, so it runs at least once |
| 3.6 | Loop | repeat forever with loop until a break leaves |
| 3.7 | Break | leave a loop early when the answer is found |
| 3.8 | Continue | skip the rest of one iteration and carry on with the next |
| 3.9 | Range | describe a run of numbers with .. and ..= |
| 3.10 | For | walk a range with for |
| 3.11 | Label | name a loop, so break can leave an outer one |
| 3.12 | Match | select a branch by value with match, and default with else |
| 3.13 | Match expression | use 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.