Skip to content
Exit presentation

Programming Proper I

A fork in the line

A rain gauge measures how much rain falls. It read six days: 4, 60, 0, 128, 12, 35 millimetres.

Loading lab…

A reading arrives: mm = 4.
Step 1 of 4
  1. A reading arrives: mm = 4.
  2. Ask: mm ≥ 60? No.
  3. Ask: mm ≥ 10? No.
  4. It is a dry day.

Each reading is sorted into a dry, wet or heavy day. Heavy means 60 or more millimetres. Wet means 10 or more, but under 60. Dry means under 10.

The rule

The condition is the yes-or-no question in the round brackets. The block is the lines inside the curly brackets.

An if runs its block only when the condition is true. In this editor, the condition must be true or false. A number or text there stops the run.

if (mm >= 10) { kind = "wet day"; }

Here mm holds one day's reading in millimetres. kind holds the name of the day.

else runs its block when the question above it was false.

The six comparison signs, read at mm = 60
SignAsksRuns to
>Bigger?false
>=Bigger or same?true
<Smaller?false
<=Smaller or same?true
===Same?true
!==Different?false

Two questions can give three answers. Ask about heavy first, then wet. The else block is for dry.

`` if (mm >= 60) { kind = "heavy day"; } else if (mm >= 10) { kind = "wet day"; } else { kind = "dry day"; } ``

An else if chain stops at the first true question. Swap the questions and every heavy day is called wet. That is because 60 or more is also 10 or more.

Take mm = 128. The first question, 128 >= 60, is true, so the day is heavy. Take mm = 12. The first question, 12 >= 60, is false. The second, 12 >= 10, is true, so the day is wet.

if (mm) { kind = "counted twice"; } is not a question. mm is a number. In this editor, the run stops:

A condition has to be true or false, but this one is a number.

Jump to lesson

This track

  1. 0 Start here
  2. 1 The same program, typed instead of dragged
  3. 2 A box you can change, and a box you cannot
  4. 3 Four kinds of value, and why the quotes matter
  5. 4 What the signs do, and the one that does two jobs
  6. 5 A fork in the line
  7. 6 A loop that runs until something stops it
  8. 7 Once for each thing you have
  9. 8 What the message says, and what it does not
  10. 9 The big picture
  11. 10 Track quiz

Other tracks