Simvik

Average the valid readings

Loop over an array of structs and use only some of them. An easy embedded C problem (Structs, enums and typedef), run and graded in the browser.

easy · Structs, enums and typedef · structs · arrays

Each reading_t has a value and a valid flag that is 1 for a good reading and 0 for a bad one.

Return the average of the value of every valid reading among the n in log, using integer division. If no reading is valid, return 0.

Starter code

typedef struct {
  int value;
  int valid;
} reading_t;

int average_valid(const reading_t *log, int n) {
  return 0;
}

Example tests

All readings valid

reading_t log[] = { { 10, 1 }, { 20, 1 }, { 30, 1 } };
printf("%d\n", average_valid(log, 3));

Expected output:

20

One bad reading is skipped

reading_t log[] = { { 10, 1 }, { 999, 0 }, { 30, 1 } };
printf("%d\n", average_valid(log, 3));

Expected output:

20

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