basics · beginner · ~15 min
Combine summation with floating-point conversion.
Compute the arithmetic mean (average) of an integer array.
Implement double mean(const int *a, size_t n) that returns the sum of the n elements of a divided by n, as a double. Return 0.0 when n is 0.
A pointer a to n ints, and the element count size_t n.
Returns the average as a double.
mean({1,2,3,4,5}, 5) -> 3.0
mean({10,10}, 2) -> 10.0
mean({}, 0) -> 0.0
n == 0 returns 0.0 (avoid dividing by zero).double before dividing so you get a real average, not integer division.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).
A pointer a to n ints, and the count size_t n.
The arithmetic mean of the elements, as a double.
Return 0.0 when n is 0.
#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.