10. LED Control Class

#include <iostream>
#include <string>
using namespace std;

class LED {
private:
    int pin;
    bool state; // true = ON, false = OFF

public:
    LED(int p) : pin(p), state(false) {} // default OFF

    void turnOn() {
        state = true;
    }

    void turnOff() {
        state = false;
    }

    void toggle() {
        state = !state;
    }

    string getState() const {
        return state ? "ON" : "OFF";
    }
};

int main() {
    int pin, n;
    cin >> pin >> n;

    LED led(pin);

    for (int i = 0; i < n; i++) {
        string op;
        cin >> op;
        if (op == "on") {
            led.turnOn();
        } else if (op == "off") {
            led.turnOff();
        } else if (op == "toggle") {
            led.toggle();
        }
    }

    cout << led.getState();
    return 0;
}

 

Solution Details

  • The class keeps pin and state private; only methods can manipulate the LED.
  • turnOn, turnOff, and toggle update the internal state.
  • getState provides a safe way to query status without exposing the raw variable.

 

Significance for Embedded Developers: This problem mimics GPIO pin control in firmware. Real-world microcontrollers require functions to drive pins HIGH/LOW or toggle them. By abstracting LED behavior into a class, code becomes reusable, modular, and easier to test in simulation.

 

Loading...

Input

13 3 on toggle toggle

Expected Output

ON