basics · beginner · ~15 min

Array mean

Combine summation with floating-point conversion.

Challenge

Compute the arithmetic mean (average) of an integer array.

Task

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.

Input

A pointer a to n ints, and the element count size_t n.

Output

Returns the average as a double.

Example

mean({1,2,3,4,5}, 5)   ->   3.0
mean({10,10}, 2)       ->   10.0
mean({}, 0)            ->   0.0

Edge cases

  • n == 0 returns 0.0 (avoid dividing by zero).

Rules

  • Cast to double before dividing so you get a real average, not integer division.

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

Input format

A pointer a to n ints, and the count size_t n.

Output format

The arithmetic mean of the elements, as a double.

Constraints

Return 0.0 when n is 0.

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.