94. Filter Structs by Field Value for example Sensor Threshold

#include <stdio.h>
#include <stdint.h>

struct Sensor {
    char name[10];
    uint8_t value;
};

// Filter and print only those sensors with value >= threshold
void print_above_threshold(struct Sensor sensors[], uint8_t n, uint8_t threshold) {
    for (uint8_t i = 0; i < n; i++) {
        if (sensors[i].value >= threshold) {
            printf("%s %u\n", sensors[i].name, sensors[i].value);
        }
    }
}

int main() {
    uint8_t n, threshold;
    scanf("%hhu %hhu", &n, &threshold);

    struct Sensor sensors[100];
    for (uint8_t i = 0; i < n; i++) {
        scanf("%s %hhu", sensors[i].name, &sensors[i].value);
    }

    print_above_threshold(sensors, n, threshold);
    return 0;
}

Why It’s Important in Firmware?

  • Used in filtering sensor logs, faults, or diagnostics
  • Useful in prioritizing events (e.g., temperature > limit)
  • Basis for embedded data processing with constrained resources

Logic Summary

  • Loop through all n sensors
  • If value >= threshold, print name and value

     
Loading...

Input

4 50 T1 45 T2 67 T3 10 T4 90

Expected Output

T2 67 T4 90