Skip to content
RoboLearn
Not completed

Conditional logic (if / else)

Control & autonomyBeginner25 minProgram decisions ↓Before this: Arduino C++ basics

What you’ll learn

  • if, else if and else
  • Comparison operators
  • Combining conditions with and, or and not

if / else if / else

if (distance() < 15) {
motors(-50, -50); // very close: back up
} else if (distance() < 40) {
motors(-40, 40); // close: turn
} else {
motors(60, 60); // clear: drive
}

The robot checks the conditions in order and runs the first one that’s true. Put the most specific or most urgent condition first.

Comparisons

Operator Means
< / > less than / greater than
<= / >= less or equal / greater or equal
== (C++) / === (JavaScript) equal to
!= / !== not equal to

Combining conditions

Operator Means Example
&& and: both must be true lineLeft() && lineRight()
|| or: at least one is true distanceLeft() < 10 || distanceRight() < 10
! not: flips true and false !lineLeft()

Finished this lesson?