Part 2: Operators

Part 1 gave you values and names for them. This part combines them: adding and dividing numbers, comparing them, joining yes-or-no answers into bigger conditions, and updating a variable in place. It is a short part — five lessons — but every program you write from here on is built from these operators, and the comparisons and conditions are exactly what Part 3 needs to make decisions.

What you will learn

  • Arithmetic with + - * / %, and why 17 / 5 is 3 for integers but 3.4 for floats.
  • Comparing values with == != < <= > >=, and why exact == between floats is risky.
  • Combining conditions with &&, || and !, and how short-circuiting lets one side guard the other.
  • Updating a variable with +=, -= and friends, and stepping it with ++ and --.
  • Which operator applies first, how same-rank operators group, and when to add parentheses.

What each kind of operator produces

flowchart LR
    n["Numbers"] -- "+ - * / %" --> n2["A number"]
    n -- "== != < <= > >=" --> b["A bool"]
    b -- "&& || !" --> b2["A bool"]
    v["A var"] -- "+= -= ++ --" --> v2["The same var,<br/>updated in place"]
    b2 --> cf["Conditions for<br/>Part 3: Control flow"]
    b --> cf

Lessons

LessonWhat you will learn
2.1Arithmeticadd, subtract, multiply, divide and take the remainder
2.2Comparisoncompare two values with ==, !=, <, <=, > and >=
2.3Logicalcombine conditions with &&, || and !
2.4Assignmentupdate a variable in place with +=, -=, ++ and friends
2.5Precedencewhich operator binds first, and how parentheses change it

Before you start

Finish Part 1: Basics first — especially Variable, Mutable, the number types and Convert. Each lesson's package is in the Examples repository's Operators/ folder:

cd Examples/Operators/Arithmetic
rux run

After this part

Part 3: Control flow puts the conditions you can now write to work, making programs choose between paths and repeat. After it come the first checkpoint projects, Thanks and FizzBuzz — FizzBuzz in particular is built on %, == and += from this part.

For the full rules, see Operations — arithmetic, comparison and logical — and the operator list in the Rux Reference.