65. SensorBuffer Fixed Storage

#include <iostream>
using namespace std;

class SensorBuffer {
private:
    int id;
    int data[5];
    int count;

public:
    SensorBuffer(int sensorId) : id(sensorId), count(0) {}

    void addSample(int v) {
        if (count < 5) {
            data[count] = v;
            count++;
        }
    }

    int size() {
        return count;
    }

    void print() {
        for (int i = 0; i < count; i++) {
            cout << data[i];
            if (i + 1 < count) cout << " ";
        }
    }
};

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

    SensorBuffer buf(id);

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        buf.addSample(x);
    }

    buf.print();
    return 0;
}

Explanation & Logic Summary:

  • Uses a fixed-size array to model memory-constrained firmware storage
  • Overflow is prevented by bounds checking
  • Data is stored sequentially in insertion order
  • Encapsulation ensures controlled access and safety

Firmware Relevance & Real-World Context:

  • Fixed-size buffers are common in MCU firmware (ADC, UART, telemetry)
  • Avoids dynamic memory allocation
  • Demonstrates safe bounds checking
  • Reflects real embedded constraints and coding practices

 

 

 

 

Loading...

Input

42 7 10 20 30 40 50 60 70

Expected Output

10 20 30 40 50