basics · beginner · ~15 min

Array mean

Combine summation with floating-point conversion.

Challenge

Implement double mean(const int *a, size_t n) returning the arithmetic mean of a. If n is 0, return 0.0.

Why this matters

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).

Starter code

#include <stddef.h>
double mean(const int *a, size_t n) { /* TODO */ return 0.0; }

Common mistakes

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).

Edge cases to handle

Empty array — return 0.0 (or NaN, or signal an error). Single element. All-negative numbers.

Complexity

O(n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.