14. Sensor with Thresholds Class

#include <iostream>
using namespace std;

class Sensor {
private:
    int id;
    int value;

public:
    Sensor(int id_, int value_) : id(id_), value(value_) {}

    void setValue(int v) {
        value = v;
    }

    bool isAboveThreshold(int t) const {
        return value >= t;
    }

    int getId() const {
        return id;
    }
};

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        int id, val, th;
        cin >> id >> val >> th;

        Sensor s(id, val);

        if (s.isAboveThreshold(th))
            cout << "Sensor " << s.getId() << ": ALERT\n";
        else
            cout << "Sensor " << s.getId() << ": NORMAL\n";
    }
    return 0;
}

 

Solution Details

  • Encapsulates sensor state (id, value) with behavior (isAboveThreshold).
     
  • Uses a clear API: construct, optionally setValue, and query via isAboveThreshold.
     
  • Prints per-sensor status, showing how multiple instances are handled independently.
     
  • Significance for Embedded Developers: Threshold checks are ubiquitous (alarms, limit detection, fault flags). Modeling each sensor as an object keeps logic localized, supports many instances (like multiple channels), and mirrors how firmware organizes drivers/HAL components cleanly.
Loading...

Input

3 101 75 60 202 30 50 303 100 100

Expected Output

Sensor 101: ALERT Sensor 202: NORMAL Sensor 303: ALERT