Find Average of N Numbers in C++

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
Loops & I/O

What you’ll learn

  • The arithmetic mean formula and how it maps to a sum loop in C.
  • A scanf-based program for N interactive inputs, plus an array version without stdin.
  • Why double and dividing by (double)N matter, and what breaks when N = 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 std::cin.

  • for loops, double and int types, and printf format specifiers such as %.6f.
  • Basic idea of integer promotion and why sum / n can 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.

Mean sum ÷ count
Median middle after sort
Mode most frequent

Formal definition

Given real numbers x1, …, xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.

Worked example

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.

1 – 5 Mean 3
Sum
1 + 2 + 3 + 4 + 5 = 15
Count
N = 5
Mean
15 / 5 = 3 (matches the sample program output).
10 – 30 Mean 20
Sum
10 + 15 + 20 + 25 + 30 = 100
Count
N = 5
Mean
100 / 5 = 20.
Trap int / int
Example
int sum = 3, n = 2
sum / n
Evaluates as integer division: 1, not 1.5.
Fix
Use double for sum or 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.

  1. Try 1, 2, 3, 4, 5 or 10,15,20,25,30.
  2. Press Run (or Enter).
  3. Compare with your C output for the same list.

Uses normal JavaScript floating point (not arbitrary precision).

Live result
Press “Run” to see count, sum, and mean.

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

Pseudocode
function averageOfN(n):
    if n <= 0:
        return error
    sum ← 0
    repeat n times:
        read x
        sum ← sum + x
    return sum / n
1

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.

c++
#include <iostream>

/* 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;
    }

    std::cout << "Enter " << n << " numbers:\n";

    for (i = 0; i < n; ++i) {
        if (!(std::cin >> x)) {
            return 0.0;
        }
        sum += x;
    }

    return sum / (double)n;
}

int main() {
    int n = 5;
    double result;

    if (n <= 0) {
        std::cout << "N must be positive.\n";
        return 1;
    }

    result = findAverage(n);
    std::cout << "The average of the entered numbers is: " << result << "\n";

    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.

2

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.

c++
#include <iostream>

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() {
    double data[] = { 10, 15, 20, 25, 30 };
    int n = (int)(sizeof data / sizeof data[0]);
    double avg = average_from_array(data, n);

    std::cout << "Average = " << avg << "\n";
    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

Add all N values to get a running sum, then divide that sum by N. In symbols: mean = (x1 + x2 + ... + xN) / N.
If inputs are fractional or you divide integers without casting, you can lose precision. Accumulating in double and dividing by (double)N avoids the classic int sum / n truncation bug for integer-only data too, when N does not divide the sum evenly.
Division by zero is undefined in C. Always validate N > 0 before dividing, or return a sentinel / error code when N is invalid.
In production code, check the return value of scanf. If the user types text instead of a number, the loop can mis-count inputs unless you handle errors or flush bad input.
Reading and summing N values is O(N) time and O(1) extra space if you only keep a running sum. Storing all values in an array first is still O(N) time but O(N) space.
No. The mean is the sum divided by the count. The median is the middle value after sorting (or the average of the two middle values). They answer different questions about the same list.

🔄 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 promptPrinted average (example)
1 2 3 4 53.000000
10 15 20 25 3020.000000
2.5 3.5 with n = 23.000000

Example 2 prints a single line:

Console
Average = 20.000000

Edge cases and pitfalls

Most real-world bugs are about types, divide-by-zero, or bad input—not the formula itself.

Zero

N == 0

Never divide by N until you know it is positive.

Types

Integer division

If sum and n are both integers, sum / n truncates. Promote before dividing.

I/O

scanf failures

Non-numeric input can leave the stream in a bad state. Check return values and consider flushing or bailing out.

Overflow

Huge sums

For extreme magnitudes or many terms, double rounding can matter; widen or use compensated summation.

⏱️ Time and space complexity

ApproachTimeExtra space
Running sum over N inputsO(N)O(1)
Store all values then sumO(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 N for N > 0.
  • Code: double accumulator, scanf("%lf") in a loop, divide by (double)N.
  • Watch-outs: N = 0, integer division, and unchecked scanf.
Did you know?

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

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful