Formula
sum / N
Average = (x1 + x2 + … + xN) / N when N > 0.
The arithmetic mean of N numbers is their sum divided by N. This tutorial covers the formula, a live preview, algorithm steps, worked PHP examples, edge cases, and complexity.
sum / N
Average = (x1 + x2 + … + xN) / N when N > 0.
O(1) space
Add each value into a total, then divide once at the end.
Read N values
Ask for N, then read N numbers from the user and accumulate.
sum / len
When values are already in an array, use array_sum($a) / count($a).
Try any set
Paste comma-separated numbers and see count, sum, and mean instantly.
Complexity
One pass over the values; extra space is O(1) or O(N) depending on storage.
The average (arithmetic mean) of N numbers is their total sum divided by how many numbers you have. In code you usually keep a running sum, then divide by N once at the end.
This page focuses on arithmetic mean — not median or mode. You will see an input-loop version, an array-based helper, and a short array_sum / count variant.
It trains loops, accumulation, division safety, and float output — fundamentals every beginner interview expects.
One pass to add, one division for the mean.
Average is undefined when the count is zero.
Means are often fractional — prefer float division.
Median needs sorting; average only needs sum and count.
In short: add the N numbers, divide by N (when N > 0), and that quotient is the average.
Given N positive count and N numeric values, compute their arithmetic mean.
# Example: 1, 2, 3, 4, 5
# Sum = 15, N = 5
# Average = 15 / 5 = 3.0 | Item | Type | Description |
|---|---|---|
N / values | int / floats | Count of numbers and the numbers themselves (N must be > 0). |
| Return / print | float / text | Arithmetic mean sum / N. |
function averageOfN(n):
if n <= 0:
return error
sum = 0
repeat n times:
read x
sum = sum + x
return sum / n | Method | Idea | Extra space |
|---|---|---|
| Running sum | Accumulate while reading; divide at end | O(1) |
| Array then mean | Store all values; array_sum / count | O(N) |
| Goal | Pattern |
|---|---|
| Formula | average = sum / N |
| Running total | total += value |
| Array mean | array_sum($a) / count($a) |
| Empty guard | if n <= 0 or if not values |
| Stdlib helper | array_sum($a) / count($a) |
| Pretty print | f"{avg:.6f}" |
Related stats words — different algorithms.
sum / NThis tutorial — one pass sum, then divide
middle after sortNeeds ordered data; not the same as average
most frequentCounts occurrences; different problem entirely
name meanSay “arithmetic mean” so interviewers know you mean sum/N
Reach for average drills when sum loops and division safety matter.
Quick check of loops, accumulation, and empty-input handling.
Classic first program after learning for and fgets(STDIN).
Scores, temperatures, and sensor readings often need a mean.
Running-sum style works when you cannot store the whole array.
If outliers matter, interviewers may ask for median instead — clarify first.
Key benefit: one tiny problem that covers loops, floats, divide-by-zero, and O(N) complexity talk.
Enter comma-separated numbers and view count, sum, and average.
Three complete PHP programs — input loop, array helper, and array_sum / count. Click View Output to reveal sample console results.
Read N values from the console and accumulate.
Validate N, loop N times, keep a running total, then divide.
<?php
function findAverageFromStdin(int $n): float
{
if ($n <= 0) {
return 0.0;
}
$sum = 0.0;
echo "Enter $n numbers:\n";
for ($i = 0; $i < $n; $i++) {
$line = trim(fgets(STDIN));
$sum += (float) $line;
}
return $sum / (float) $n;
}
$n = 5;
$result = findAverageFromStdin($n);
echo "The average of the entered numbers is: " . number_format($result, 6) . "\n";
?> Guard non-positive N, accumulate floats into total, then return total / n. Casting to float keeps fractional means clear for common school examples.
When the values already live in an array.
Use a foreach loop (or array_sum / count) when values are already in memory.
<?php
function averageFromArray(array $a): float
{
$n = count($a);
if ($n <= 0) {
return 0.0;
}
$sum = 0.0;
foreach ($a as $x) {
$sum += (float) $x;
}
return $sum / (float) $n;
}
$data = [10, 15, 20, 25, 30];
$avg = averageFromArray($data);
echo "Average = " . number_format($avg, 6) . "\n";
?> Empty arrays return a documented sentinel (0.0 here). Otherwise a running sum divided by count($a) is exactly the arithmetic mean.
Same math via array_sum and count.
array_sum / countPrefer this in application code when a non-empty array is guaranteed.
<?php
$data = [1, 2, 3, 4, 5];
$n = count($data);
echo $n > 0 ? (array_sum($data) / $n) . "\n" : "empty\n";
?> array_sum($data) / count($data) computes the arithmetic mean of a non-empty array. Always guard empty arrays — dividing by zero is an error.
If the count is zero or negative, stop — division would be invalid.
Add each number into a running total (or call array_sum on an array).
Compute $total / $n (or array_sum / count) as a float mean.
Print or return the quotient — that is the arithmetic mean.
1, 2, 3, 4, 5Trace a running-sum loop for five values. Start with total = 0.0 and N = 5.
| Step | Value | total after add |
|---|---|---|
| 1 | 1 | 1.0 |
| 2 | 2 | 3.0 |
| 3 | 3 | 6.0 |
| 4 | 4 | 10.0 |
| 5 | 5 | 15.0 |
Final mean: 15.0 / 5 = 3.0.
Where average-of-N checks show up beyond the interview prompt.
Tests loops, floats, and empty-input guards.
Example: write average_of_n(n).
Class marks or game scores often need a mean.
Example: average of five test scores.
Smooth noisy measurements with a simple mean.
Example: average of last N samples.
Makes running totals feel concrete before harder stats.
Example: chalkboard sum of 1…5.
O(1) extra space when you cannot store every value.
Example: online mean while reading a file.
Argue O(N) time and O(1) vs O(N) space cleanly.
Example: loop vs array storage.
Pro Tip: keep a pure averageFromArray helper and wrap input separately — easier to test.
Why this pattern works well in interviews and classwork.
Sum then divide — almost no translation gap from math to code.
A running total never needs to store the full array.
sum, len, and array_sum / count keep production code short.
Empty / N=0 is an obvious safety point interviewers love to hear.
Pro Tip: say “arithmetic mean = sum / count” before coding — it frames the whole solution.
Small habits that keep average code interview-ready.
Check N > 0 or non-empty arrays before dividing.
Start with total = 0.0 so fractional means stay natural.
Parse values first, then call a pure average helper.
Assert 1…5 → 3.0 and 10…30 step 5 → 20.0.
Ask whether to return 0, raise, or None when N is zero.
Pro Tip: dry-run 1…5 on paper once — it catches off-by-one loop bounds faster than guessing.
Mistakes that commonly break average solutions.
Empty arrays or N = 0 crash or return nonsense.
→ Validate count before the division.
Sorting and picking the middle value is a different algorithm.
→ Confirm the prompt asks for arithmetic mean.
Cast to float when you want clear decimal output — be explicit about the division type.
→ Use floats or format the printed mean clearly.
Non-numeric strings break (float) fgets or parsers.
→ Catch conversion errors in production code.
Reading N-1 or N+1 values skews the mean.
→ Loop exactly for ($i = 0; $i < $n; $i++) and trust that count.
Check these inputs before calling the solution done.
Always validate count before dividing.
Return a sentinel, raise, or error — do not divide.
Average of a single number is itself.
Handle conversion errors in production code.
Means can be negative; do not reject signed numbers.
Printed decimals may show tiny floating-point noise.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
array_sum / countQuick Takeaway: add the numbers, divide by how many there are — and never divide by zero.
| Program | Time | Extra space |
|---|---|---|
| Running sum loop | O(N) | O(1) |
| Store array then compute | O(N) | O(N) |
array_sum / count | O(N) | depends on input storage |
Finding the average of N numbers is a clean accumulation exercise: validate the count, sum the values, divide once. Master the input loop and the array helper, then mention array_sum / count for application code.
Practice the three examples above, then continue to biggest-of-three-numbers for another classic comparison warm-up.
Never divide by zero, never confuse mean with median, and always state O(N) when asked about complexity.
Compute the mean the interview-friendly way.
sum / N
DefinitionRunning total
CodeN must be > 0
Guardsum / count
CodeO(N) time
AnalysisThe arithmetic mean is the common school-level average: add all values and divide by how many values you have.
Learn how to find the largest value among three numbers in PHP.
9 people found this page helpful