What are Conditionals?
Conditionals let your program make decisions. Based on whether a condition is true or false, different code runs.
Basic If Statement
if (temperature > 30) {
Serial.println("It's hot!");
}
If/Else
if (buttonPressed) {
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}
If/Else If/Else
if (score >= 90) {
Serial.println("A");
} else if (score >= 80) {
Serial.println("B");
} else if (score >= 70) {
Serial.println("C");
} else {
Serial.println("F");
}
Comparison Operators
| Operator | Meaning | |----------|---------| | == | Equal to | | != | Not equal to | | < | Less than | | > | Greater than | | <= | Less than or equal | | >= | Greater than or equal |
Logical Operators
| Operator | Meaning | Example | |----------|---------|---------| | && | AND | if (a > 5 && b < 10) | | \|\| | OR | if (a > 5 \|\| b < 10) | | ! | NOT | if (!isLocked) |
Common Mistake
// WRONG: this is assignment, not comparison!
if (x = 5) { }
// CORRECT: comparison
if (x == 5) { }