21. Dynamic Sensor Buffer

#include <iostream>

int main() {
    int n;
    std::cin >> n;

    if (n < 1) {
        return 0;
    }

    int* samples = new int[n];   // dynamic sensor buffer

    int sum = 0;
    for (int i = 0; i < n; i++) {
        std::cin >> samples[i];
        sum += samples[i];
    }

    int average = sum / n;       // integer division
    std::cout << average;

    delete[] samples;            // free allocated memory
    return 0;
}

Explanation & Logic Summary:

  • Sensor burst size is determined at runtime, requiring dynamic allocation.
  • new[] allocates memory sized exactly to the required number of samples.
  • Sensor readings are accumulated and averaged using integer arithmetic.
  • delete[] is required to prevent memory leaks in long-running firmware systems.

Firmware Relevance & Real-World Context:

  • Embedded firmware frequently handles variable-length data buffers:
    • ADC sampling bursts
    • IMU or sensor fusion windows
    • UART or DMA receive buffers
  • Dynamic allocation must be used carefully:
    • Allocate only when necessary
    • Release immediately after use
    • Avoid long-lived heap usage
  • This task evaluates:
    • Heap usage discipline
    • Memory lifecycle awareness
    • Safe handling of runtime-sized data

 

 

 

 

Loading...

Input

5 10 20 30 40 50

Expected Output

30