Calculate an array average
Calculate the arithmetic mean of a non-empty integer array and return a floating-point result.
Course progress
Problem 52 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [4, 7, 9, 6]
Expected output
6.5
What is happening?
The values total 26. Dividing by the four array items gives an average of 6.5.
Solution strategy
Build the right mental model
Accumulate the values in a long to reduce overflow risk, then divide by the item count using floating-point division.
Core concepts
arrays · arithmetic
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for average-array-values
using System;
class Program
{
static double Average(int[] numbers)
{
if (numbers.Length == 0) throw new ArgumentException("Array cannot be empty.");
long total = 0;
foreach (int number in numbers) total += number;
return (double)total / numbers.Length;
}
static void Main()
{
Console.WriteLine(Average(new[] { 4, 7, 9, 6 }).ToString("0.0"));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate an array average?
Accumulate the values in a long to reduce overflow risk, then divide by the item count using floating-point division.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.