Simvik

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:

2

All on

led_t leds[] = { { 2, LED_ON }, { 3, LED_ON } };
printf("%d\n", count_on(leds, 2));

Expected output:

2

Learn 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