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 (or one line split into tokens).
  • A console program that reads N numbers, plus an array version without interactive input.
  • Why double for the running total matters, and what breaks when N = 0.
  • A small browser live preview for comma-separated numbers.

Overview

This walkthrough shows how to read N numeric values, add them into one running total, 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 console sample for N numbers on one line, plus a fixed array example.

Live preview

Paste comma-separated values and see count, sum, and mean instantly.

Interview polish

Guards for N ≤ 0, integer-division traps, and TryParse instead of trusting raw text.

Prerequisites

You should know how to create a small console app and read text with Console.ReadLine().

  • for loops, double and int, and formatting with something like {value:F6}.
  • Why sum / n can silently drop fractions when both operands are 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 keep one accumulator sum, add each value, 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.

Use this list as a quick 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
Integer division in C#: 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.

Choose N

Decide how many numbers will be averaged. If N ≤ 0, stop or report an error before dividing.

Initialize sum = 0

Use double for sum so fractional inputs and non-integer means behave predictably.

Collect N numbers

Either read one line and split into tokens, or read N lines in a loop. Add each parsed value to sum.

Divide

Return sum / N when sum is double so the division stays floating-point (or use (double) casts intentionally).

📜 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 the console

Prompts for N numbers on one line (spaces between values). That matches the usual demo where you type 1 2 3 4 5 and press Enter. Uses double.TryParse with invariant culture so 3.5 parses the same everywhere.

c#
using System;
using System.Globalization;

class Program
{
    static double FindAverage(int n)
    {
        if (n <= 0)
        {
            return 0.0;
        }

        Console.WriteLine($"Enter {n} numbers:");
        string? line = Console.ReadLine();
        if (string.IsNullOrWhiteSpace(line))
        {
            return 0.0;
        }

        string[] parts = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length < n)
        {
            return 0.0;
        }

        double sum = 0.0;
        for (int i = 0; i < n; i++)
        {
            if (!double.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out double x))
            {
                return 0.0;
            }
            sum += x;
        }

        return sum / n;
    }

    static void Main()
    {
        int n = 5;

        if (n <= 0)
        {
            Console.WriteLine("N must be positive.");
            return;
        }

        double result = FindAverage(n);
        Console.WriteLine($"The average of the entered numbers is: {result:F6}");
    }
}

Explanation

The method reads every value from a single line, sums them, then divides once.

if (n <= 0) return 0.0;

Guard division. Skips undefined mean when there is nothing to average.

line.Split(..., RemoveEmptyEntries)

Tokens. Turns "1 2 3 4 5" into five strings without manual trimming loops.

return sum / n;

Floating division. sum is double, so n promotes and you get 3.0, not truncated integer math.

2

Average from a fixed array (no console)

Same mean as the prose example: 10, 15, 20, 25, 30 → mean 20. Handy when values are known at compile time or already in memory.

c#
using System;

class Program
{
    static double AverageFromArray(double[]? a)
    {
        if (a == null || a.Length == 0)
        {
            return 0.0;
        }

        double sum = 0.0;
        foreach (double x in a)
        {
            sum += x;
        }

        return sum / a.Length;
    }

    static void Main()
    {
        double[] data = { 10, 15, 20, 25, 30 };
        double avg = AverageFromArray(data);
        Console.WriteLine($"Average = {avg:F6}");
    }
}

Explanation

data.Length is the element count for this array instance.

foreach (double x in a)

Clear iteration. Same mathematics as an indexed for, often easier to read.

if (a == null || a.Length == 0)

Safe helper. Interview-friendly guard before touching elements.

Optimization

One pass. You do not need to store every value just for the mean; a running sum is enough unless you also compute median, variance, etc.

Very large N or huge magnitudes. Plain double accumulation can drift; advanced fixes include Kahan summation or decimal for money-like data.

Online mean. Streaming updates use meank = meank-1 + (xk - meank-1) / k so you never store 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 have fractions or you divide two integers with /, you can lose the fractional part. Keeping sum as double (and dividing by N when sum is double, or casting with (double)) avoids the classic truncation bug.
The mean is not defined when there are no values. Integer division by zero throws DivideByZeroException in C#. For doubles, dividing by 0.0 yields Infinity or NaN instead of a useful average—so always validate N > 0 before dividing.
Read a line with Console.ReadLine(), then split on spaces or loop N times for N lines. Always validate with double.TryParse (or handle FormatException from double.Parse) when input might not be numeric.
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

For Example 1 with n = 5, type five numbers separated by spaces after the prompt.

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 impossible input—not the formula itself.

Zero

N == 0

Never divide until N is confirmed positive.

Types

Integer division

Two integers with / truncate toward zero in C#. Promote first when you need decimals.

I/O

Bad console text

Letters or empty tokens fail TryParse; decide whether to retry, skip, or exit cleanly.

Culture

Commas vs dots

Some locales use 3,5 instead of 3.5. Invariant culture keeps tutorials reproducible; UI apps often use the user’s culture on purpose.

⏱️ 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 here keep only a few scalars beyond the input buffer: auxiliary space stays constant relative to extra allocations.

Summary

  • Mean: add all values, divide by N for N > 0.
  • Code: double accumulator, parse tokens, divide with floating math.
  • Watch-outs: N = 0, integer division, invalid input, locale quirks.
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