Count the LEDs that are on
Combine a struct, an enum member and a loop. An easy embedded C problem (Structs, enums and typedef), run and graded in the browser.
easy · Structs, enums and typedef · structs · enums · arrays
Each led_t has a pin and a state, which is LED_OFF or LED_ON.
Return how many of the n LEDs in leds are on.
Starter code
typedef enum { LED_OFF, LED_ON } led_state_t;
typedef struct {
int pin;
led_state_t state;
} led_t;
int count_on(const led_t *leds, int n) {
return 0;
}Example tests
Some on, some off
led_t leds[] = { { 13, LED_ON }, { 12, LED_OFF }, { 11, LED_ON } };
printf("%d\n", count_on(leds, 3));Expected output:
2All on
led_t leds[] = { { 2, LED_ON }, { 3, LED_ON } };
printf("%d\n", count_on(leds, 2));Expected output:
2Learn it first
- Structs, enums and typedef · Grouping values into structs, the dot and the arrow, naming choices with enum, and shorter names with typedef.
More Structs, enums and typedef problems
- Build a struct · Fill in a struct's members and return it.
- Distance between two points · Read the members of two structs passed by value.
- Move a point · Change the caller's struct through a pointer.
- Average the valid readings · Loop over an array of structs and use only some of them.
- The next traffic light colour · Step through the states of an enum.