C program to input real numbers and find the mean, variance and standard deviation

Given N real numbers, this program computes three fundamental descriptive statistics: the mean (arithmetic average), the variance (how spread out the values are from the mean), and the standard deviation (the square root of variance — in the same units as the data). These are the first three statistics taught in any probability or data analysis course, and they appear everywhere from quality control and sensor calibration to machine learning feature engineering.

The original post used conio.h, void main(), and float for all computations. This rewrite uses double throughout (more precision, avoids float rounding surprises), checks scanf return values, and calls sqrt() from <math.h>.

Formulas

Statistic Formula What It Measures
Mean (μ) μ = (Σxᵢ) / n Center of the data
Variance (σ²) σ² = Σ(xᵢ − μ)² / n Average squared deviation from mean
Std Deviation (σ) σ = √(σ²) Spread in same units as data

Note: This program computes population variance (÷ n), not sample variance (÷ n−1). Use ÷ (n−1) when the data is a sample drawn from a larger population (Bessel’s correction).

C Program: Mean, Variance, and Standard Deviation

/* Mean, variance, and standard deviation of N real numbers
 * Compile: gcc -ansi -Wall -Wextra stats.c -o stats -lm */
#include <stdio.h>
#include <math.h>

#define MAX 100

int main(void)
{
    double a[MAX], sum, mean, variance, stddev;
    int i, n;

    printf("Enter number of values (max %d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid count.\n");
        return 1;
    }

    printf("Enter %d values:\n", n);
    sum = 0.0;
    for (i = 0; i < n; i++) {
        if (scanf("%lf", &a[i]) != 1) { printf("Invalid input.\n"); return 1; }
        sum += a[i];
    }

    mean = sum / n;

    variance = 0.0;
    for (i = 0; i < n; i++)
        variance += (a[i] - mean) * (a[i] - mean);
    variance /= n;  /* population variance */

    stddev = sqrt(variance);

    printf("\nCount    = %d\n", n);
    printf("Sum      = %.4f\n", sum);
    printf("Mean     = %.4f\n", mean);
    printf("Variance = %.4f\n", variance);
    printf("Std Dev  = %.4f\n", stddev);

    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra stats.c -o stats -lm
./stats

The -lm flag links the math library, required for sqrt().

Sample Output

Enter number of values (max 100): 5
Enter 5 values:
2 4 6 8 10

Count    = 5
Sum      = 30.0000
Mean     = 6.0000
Variance = 8.0000
Std Dev  = 2.8284

Worked Example — Verify by Hand

Data: 2, 4, 6, 8, 10

xᵢ xᵢ − μ (xᵢ − μ)²
2 2 − 6 = −4 16
4 4 − 6 = −2 4
6 6 − 6 = 0 0
8 8 − 6 = 2 4
10 10 − 6 = 4 16
Sum of squares 40

Mean = 30/5 = 6. Variance = 40/5 = 8. StdDev = √8 ≈ 2.8284. Matches the program output.

Code Explanation

  • Two-pass algorithm — pass 1 accumulates the sum to compute the mean. Pass 2 computes the sum of squared deviations from that mean. A one-pass algorithm exists (Welford’s method) that numerically stable for streaming data, but two passes is simpler to understand and accurate for small arrays.
  • Use double, not float — float has only ~7 decimal digits of precision. With many values or values close together, floating-point cancellation error can corrupt the variance. double gives ~15 digits and is what sqrt() takes and returns. Use %lf in scanf() for double (required in C89/C90; not needed in C99+ but harmless).
  • sqrt() from <math.h> — computes the square root. Must link with -lm on most Unix systems. On Windows/MSVC, the math library is linked automatically.
  • Population vs sample variance — dividing by n gives population variance. For statistical inference from a sample, divide by (n−1). Most calculator apps and Excel’s VAR function use n−1. Python’s statistics.variance() uses n−1 by default; statistics.pvariance() uses n.

What This Program Teaches

  • Two-pass averaging pattern — storing all values then computing deviations in a second pass is a clean, readable approach to statistics. For very large datasets, Welford’s online algorithm computes mean and variance in one pass without storing all values.
  • double vs float for numerical work — always prefer double. The extra 8 bytes per value is rarely a bottleneck; the lost precision of float almost always is.
  • -lm linking — C’s standard math functions (sqrt, sin, cos, log, pow, etc.) live in a separate math library. Forgetting -lm gives a linker error: “undefined reference to sqrt”.
  • Practical use of these statistics — a small stddev means data clusters tightly around the mean (precise sensor, consistent manufacturing). A large stddev means high variability. The “68-95-99.7 rule” says 68% of a normal distribution falls within ±1σ of the mean.

Related Programs

Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
 | 
C Programming: A Modern Approach — K.N. King (India) |
(US)

Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>