Menu
CoddyTech

Combining Conditions

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

Two conditions can be joined into one:

  • && means and: true only when both sides are true
  • || means or: true when at least one side is true
if (count >= 3 && count <= 7) { ... }   // 3, 4, 5, 6 or 7
if (count == 1 || count == 9) { ... }   // 1 or 9

The first reads "count is at least 3 and at most 7": a range. The second reads "count is 1 or count is 9".

Each side must be a whole comparison. count == 1 || 9 does not mean "1 or 9": the right side is 9 on its own, which the board treats as true, so the whole condition is always true.

And count >= 3 || count <= 7 is always true too, because every number is either at least 3 or at most 7. A range needs &&.

challenge icon

Challenge

Medium

The starter counts up every 300 ms. Red LED on pin 8, green LED on pin 9. Each time round:

  • turn green on when count is from 4 to 6 (4, 5 or 6), and off otherwise
  • turn red on when count is 2 or 8, and off otherwise

Press Run, then Check.

Try it yourself

int count = 0;

void setup() {
  pinMode(8, OUTPUT);  // red
  pinMode(9, OUTPUT);  // green
  Serial.begin(9600);
}

void loop() {
  count = count + 1;
  Serial.println(count);
  // green on from 4 to 6, red on at 2 and at 8
  delay(300);
}
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