Filter Structs by Field Value for example Sensor Threshold

iterate through struct array and print

 

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

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

void print_above_threshold(const struct Sensor sensors[], uint8_t n, uint8_t threshold) {
    // Your logic here
    uint8_t t;
    for(t = 0; t<n; t++){
        if(sensors[t].value >= threshold){
            printf("%s %hhu\n",sensors[t].name, sensors[t].value );
            //if(t < n-1) putchar('\n');
        }
    }
}

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;
}

Solving Approach

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

 

 

 

Upvote
Downvote
Loading...

Input

4 50 T1 45 T2 67 T3 10 T4 90

Expected Output

T2 67 T4 90