- Sum
1 + 2 + 3 + 4 + 5 = 15- Count
N = 5- Mean
15 / 5 = 3(matches the sample program output).
Find Average of N Numbers in C
What you’ll learn
- The arithmetic mean formula and how it maps to a sum loop in C.
- A scanf-based program for
Ninteractive inputs, plus an array version without stdin. - Why
doubleand dividing by(double)Nmatter, and what breaks whenN = 0. - A small browser live preview for comma-separated numbers.
Overview
This walkthrough shows how to read N numeric inputs, accumulate their sum, and print the average (mean). A second program averages values already stored in an array—the same math, a different data path.
Two programs
Interactive scanf loop for N numbers, plus a fixed array example (same mean idea).
Live preview
Paste comma-separated values and see count, sum, and mean instantly.
Interview polish
Guards for N ≤ 0, integer-division traps, and optional scanf return checks.
Prerequisites
You should know how to compile a small C program and read from standard input with scanf.
forloops,doubleandinttypes, andprintfformat specifiers such as%.6f.- Basic idea of integer promotion and why
sum / ncan truncate when both look like integers.
What is the average here?
The arithmetic mean (what we call average on this page) of numbers x1, …, xN is
μ = (x1 + x2 + … + xN) / N, provided N > 0.
In code you usually maintain one accumulator sum inside a loop, then divide once at the end.
Formal definition
Given real numbers x1, …, xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.
For 10, 15, 20, 25, 30, the sum is 100 and N = 5, so μ = 100 / 5 = 20.
The reference prose used this list; it is a clean sanity check when you print intermediate sums during debugging.
Intuition and examples
Think of the mean as “flattening” every value onto one number: if you replaced every entry in the list with that number, the total would match the original sum.
- Sum
10 + 15 + 20 + 25 + 30 = 100- Count
N = 5- Mean
100 / 5 = 20.
- Example
int sum = 3, n = 2sum / n- Evaluates as integer division: 1, not 1.5.
- Fix
- Use
doubleforsumor cast:(double)sum / n.
Takeaway: the math is simple; most bugs are type bugs or N = 0.
Live preview
Enter numbers separated by commas (spaces optional). The tool parses each token as a JavaScript number, sums them, divides by the count, and prints count, sum, and mean. Empty input is rejected; at most 500 values are accepted.
- Try
1, 2, 3, 4, 5or10,15,20,25,30. - Press Run (or Enter).
- Compare with your C output for the same list.
Algorithm
Goal: read N values, compute their arithmetic mean.
Read N
Decide how many numbers will be averaged. If N ≤ 0, stop or report an error before dividing.
Initialize sum = 0
Use a floating type such as double for sum so fractional inputs and non-integer means behave predictably.
Loop N times
Each iteration reads one value and adds it to sum.
Divide
Return sum / (double)N (or an equivalent expression) so the division is floating-point.
📜 Pseudocode
function averageOfN(n):
if n <= 0:
return error
sum ← 0
repeat n times:
read x
sum ← sum + x
return sum / n Average of N numbers from stdin (scanf)
Prompts for N values, reads them with scanf("%lf", &x), and returns sum / (double)n. Checks n > 0 before dividing.
#include <stdio.h>
/* Reads n doubles from stdin; returns their mean, or 0.0 if n <= 0 */
double findAverage(int n) {
double sum = 0.0;
double x;
int i;
if (n <= 0) {
return 0.0;
}
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; ++i) {
if (scanf("%lf", &x) != 1) {
return 0.0;
}
sum += x;
}
return sum / (double)n;
}
int main(void) {
int n = 5;
double result;
if (n <= 0) {
printf("N must be positive.\n");
return 1;
}
result = findAverage(n);
printf("The average of the entered numbers is: %.6f\n", result);
return 0;
} Explanation
The function keeps one running total and only divides after every term has been read.
if (n <= 0) return 0.0;Guard division. Without this, sum / n would hit undefined behavior for n == 0.
scanf("%lf", &x)Read one double. The address-of operator attaches directly to the variable name; spaces around & are only style.
return sum / (double)n;Floating division. Casting n avoids accidentally doing the whole sum in integer arithmetic first.
Average from a fixed array (no stdin)
Same mean as the formal example: 10, 15, 20, 25, 30 → mean 20. Useful when inputs are known at compile time or already loaded into memory.
#include <stdio.h>
double average_from_array(const double a[], int n) {
double sum = 0.0;
int i;
if (n <= 0 || a == NULL) {
return 0.0;
}
for (i = 0; i < n; ++i) {
sum += a[i];
}
return sum / (double)n;
}
int main(void) {
double data[] = { 10, 15, 20, 25, 30 };
int n = (int)(sizeof data / sizeof data[0]);
double avg = average_from_array(data, n);
printf("Average = %.6f\n", avg);
return 0;
} Explanation
sizeof data / sizeof data[0] counts elements at compile time for this fixed array.
const double a[]Read-only view. The function promises not to modify caller memory while summing.
if (n <= 0 || a == NULL)Defensive API. Matches how you would harden library-style helpers in an interview follow-up.
Optimization
One pass. You never need to store all values just to compute the mean; a running sum is enough unless other statistics are required.
Very large N or huge magnitudes. Kahan summation or wider types (long double) reduce rounding error; for money, use fixed-point or decimal libraries.
Online mean. If values arrive in a stream, update with meank = meank-1 + (xk - meank-1) / k to avoid storing the full history.
Interview: state O(N) time and O(1) extra space for the streaming sum approach.
❓ FAQ
🔄 Input / output examples
When you run Example 1 with n = 5 and type five numbers on one line or across lines, scanf consumes them in order.
| Typed after the prompt | Printed average (example) |
|---|---|
1 2 3 4 5 | 3.000000 |
10 15 20 25 30 | 20.000000 |
2.5 3.5 with n = 2 | 3.000000 |
Example 2 prints a single line:
Average = 20.000000 Edge cases and pitfalls
Most real-world bugs are about types, divide-by-zero, or bad input—not the formula itself.
N == 0
Never divide by N until you know it is positive.
Integer division
If sum and n are both integers, sum / n truncates. Promote before dividing.
scanf failures
Non-numeric input can leave the stream in a bad state. Check return values and consider flushing or bailing out.
Huge sums
For extreme magnitudes or many terms, double rounding can matter; widen or use compensated summation.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
Running sum over N inputs | O(N) | O(1) |
| Store all values then sum | O(N) | O(N) for the buffer |
Both sample programs on this page use only a few scalars besides input storage: auxiliary space is constant for the streaming approach.
Summary
- Mean: add all values, divide by
NforN > 0. - Code:
doubleaccumulator,scanf("%lf")in a loop, divide by(double)N. - Watch-outs:
N = 0, integer division, and uncheckedscanf.
The arithmetic mean is the simplest “center” of a list: add every value, divide by how many there are. It matches what people usually mean by average in everyday language (and in most intro programming tasks).
9 people found this page helpful
