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:
20One bad reading is skipped
reading_t log[] = { { 10, 1 }, { 999, 0 }, { 30, 1 } };
printf("%d\n", average_valid(log, 3));Expected output:
20Learn 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.
- The next traffic light colour · Step through the states of an enum.
- Count the LEDs that are on · Combine a struct, an enum member and a loop.