Programming Fundamentals

Conditionals & Logic

12 min · 2 worked examples · 3 questionsFree

How a program makes decisions, and the classic mistakes that break them.

After this lesson you can

  • Write an if statement that does what you meant
  • Spot the = for == bug on sight
  • Combine conditions without getting the logic backwards

The if statement

A conditional runs a block of code only when something is true.

if (distance < 10) { digitalWrite(led, HIGH); }

The expression in brackets evaluates to true or false, and the block runs only if it is true. Add else for the alternative, and else if to test several possibilities in order.

This is the moment a program stops being a fixed list of instructions and starts responding to the world. Every automatic door, thermostat and alarm is fundamentally an if statement wrapped around a sensor.

In the full lesson

  1. The if statement
  2. = and == are completely different
  3. Combining conditions
  4. Comparison operators

Free with an account. Read it, work the examples, answer the questions, then build it in the simulator.