Menu
CoddyTech

Choosing with if and else

Part of the First Circuits section of Coddy's Arduino journey. Lesson 19 of 22.

else gives an if a second path, for when the condition is false:

if (count > 3) {
  Serial.println("big");
} else {
  Serial.println("small");
}

Exactly one of the two runs. The board checks the condition, takes one path, and carries on after the last brace.

With a counter, if and else let a sketch behave one way at first and another way later: count grows each time round loop(), and once it passes a number, the condition flips.

challenge icon

Challenge

Medium

Red LED on pin 8, green LED on pin 9. Make red blink five times, then green take over:

  • at the top, make int count = 0;
  • at the start of loop(), add 1 to count
  • if count is more than 5, blink green once (500 ms on, 500 ms off)
  • else, blink red once

Press Run, then Check.

Try it yourself

int count = 0;

void setup() {
  pinMode(8, OUTPUT);  // red
  pinMode(9, OUTPUT);  // green
}

void loop() {
  // add 1 to count

  // if count is more than 5, blink green, else blink red
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in First Circuits

Practice on your own: Arduino playground