Control Structure

Lesson 20 - Using else Statement

Learn how else handles the false path in decision logic so your Arduino program always has clear behavior.

Progress indicator

Lesson 20 of 28

Learning Objectives

  • Understand what else means in an if-else decision.
  • Write correct else syntax with matching braces.
  • Compare if-only and if-else behavior clearly.
  • Use beginner-friendly else if chains for multiple conditions.
  • Avoid common logic mistakes in true/false branches.

Concept Explanation

What is else Statement

else is the fallback branch of a decision. It runs when theif condition is false.

In beginner Arduino projects, else helps you define what should happen when the main condition is not met.

else Syntax

if (condition) {
  // true path
} else {
  // false path
}

How else Works

A single if-else chooses exactly one path each time it is checked.

If if is true, else is skipped. If if is false,else runs.

if vs if-else

  • if only: do something when condition is true.
  • if-else: define behavior for both true and false.

else if Chain Basics

if (score > 90) {
  grade = 'A';
} else if (score > 75) {
  grade = 'B';
} else {
  grade = 'C';
}

When to Use else

  • Turn an LED OFF when a button is not pressed
  • Show an error message when input is invalid
  • Handle the default state in control systems

Example Code

This example turns LED ON when button is pressed, otherwise it turns LED OFF.

const int buttonPin = 0;
const int ledPin = 2;
int buttonState = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH);
    Serial.println("Button pressed -> LED ON");
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println("Button not pressed -> LED OFF");
  }

  delay(100);
}

Example Code Explanation

  1. setup() configures button input and LED output.
  2. digitalRead(buttonPin) gets the current button value.
  3. if (buttonState == LOW) checks pressed state with INPUT_PULLUP logic.
  4. In the true path, LED turns ON and Serial prints pressed status.
  5. In the else path, LED turns OFF and Serial prints release status.
  6. The loop repeats forever, so this decision runs continuously.

Common Mistakes with else

  • Placing a semicolon right after if (condition);.
  • Forgetting braces, which can connect else to the wrong if.
  • Using = instead of == in conditions.
  • Ignoring INPUT_PULLUP logic where LOW often means button pressed.

Best Practices for else

  • Always write both branches clearly when outcomes differ.
  • Use meaningful variable names so condition logic is readable.
  • Prefer simple if-else blocks before creating long else-if chains.
  • Test both true and false paths in simulator or hardware.

Try it now

Open the simulator workspace and test both branches by toggling button state.

Run in Simulator