basics · beginner · ~15 min
Combine summation with floating-point conversion.
Implement double mean(const int *a, size_t n) returning the arithmetic mean of a. If n is 0, return 0.0.
Averaging an int array is the simplest 'reduce' operation. It's also a tiny lesson in floating-point conversion timing — divide ints, get an int (truncated).
#include <stddef.h>
double mean(const int *a, size_t n) { /* TODO */ return 0.0; }
Dividing by n while both are int (truncates). Forgetting the n==0 edge case (division by zero crashes). Using int for the sum (overflows for large arrays).
Empty array — return 0.0 (or NaN, or signal an error). Single element. All-negative numbers.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.