- 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 (or one line split into tokens).
- A console program that reads
Nnumbers, plus an array version without interactive input. - Why
doublefor the running total matters, and what breaks whenN = 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().
forloops,doubleandint, and formatting with something like{value:F6}.- Why
sum / ncan 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.
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.
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.
- Sum
10 + 15 + 20 + 25 + 30 = 100- Count
N = 5- Mean
100 / 5 = 20.
- Example
int sum = 3, n = 2sum / n- Integer division in C#: 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.
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
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 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.
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.
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.
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
🔄 Input / output examples
For Example 1 with n = 5, type five numbers separated by spaces after the prompt.
| 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 impossible input—not the formula itself.
N == 0
Never divide until N is confirmed positive.
Integer division
Two integers with / truncate toward zero in C#. Promote first when you need decimals.
Bad console text
Letters or empty tokens fail TryParse; decide whether to retry, skip, or exit cleanly.
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
| 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 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
NforN > 0. - Code:
doubleaccumulator, parse tokens, divide with floating math. - Watch-outs:
N = 0, integer division, invalid input, locale quirks.
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
