Easy 0 solved 0% acceptance

Array Average

Compute the average of a list of numbers.

What you'll learn

  • Sum values and divide by the count
  • Return a decimal result
  • Avoid integer division mistakes

Problem

Return the arithmetic mean of the list: its sum divided by its length, as a decimal number.

Implement array_average(numbers).

Input

numbers: A non-empty list of integers.

Output

Return the average.

Constraints

1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹

Examples

Example 1
Input:
numbers = [2, 4, 6]

Expected output:
expected = 4.0
Input:
std::vector<long long> numbers = {2, 4, 6};

Expected output:
double expected = 4.0;
Input:
long[] numbers = new long[] {2, 4, 6};

Expected output:
double expected = 4.0;

Explanation

(2 + 4 + 6) / 3 = 4.

Example 2
Input:
numbers = [1, 2]

Expected output:
expected = 1.5
Input:
std::vector<long long> numbers = {1, 2};

Expected output:
double expected = 1.5;
Input:
long[] numbers = new long[] {1, 2};

Expected output:
double expected = 1.5;

Explanation

(1 + 2) / 2 = 1.5; divide as decimals.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The average comes from combining the whole list into one total and then using its length.

Hint 2

A single pass can collect the sum, then divide by how many values there are.

Hint 3

Be careful to preserve decimal precision instead of using integer division.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.