62. LED Toggle Class

#include <iostream>
using namespace std;

class LED {
private:
    int pin;    // GPIO pin number
    int state;  // 0 = OFF, 1 = ON

public:
    // Constructor initializes pin and sets LED to OFF
    LED(int p) : pin(p), state(0) {}

    void on() {
        state = 1;
    }

    void off() {
        state = 0;
    }

    void toggle() {
        state = 1 - state;
    }

    int status() {
        return state;
    }
};

int main() {
    int pin, initialState, toggleCount;
    cin >> pin >> initialState >> toggleCount;

    LED led(pin);

    if (initialState == 1)
        led.on();
    else
        led.off();

    for (int i = 0; i < toggleCount; i++) {
        led.toggle();
    }

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

Explanation & Logic Summary:

  • The LED state is encapsulated and modified only via class methods.
  • toggle() demonstrates controlled state transitions.
  • The constructor enforces a known safe startup state.
  • The solution models a common embedded peripheral abstraction.

Firmware Relevance & Real-World Context:

  • Mirrors GPIO-driven LED control in firmware.
  • Reflects HAL-style peripheral encapsulation.
  • Reinforces state safety and interface-based control.
  • Common pattern for heartbeat LEDs, indicators, and debug signals.

 

Loading...

Input

5 1 3

Expected Output

0