Skip to main content

Standard deviation and mean of array

Short answer

Compute the mean of the array, then for each element accumulate (mean - xi)². Divide the sum by n and take the square root to get standard deviation. Use separate functions for mean and standard deviation.

Write a pseudocode to find the standard deviation of an array of values in C programming. The array elements are read from the terminal. Use user defined functions to calculate standard deviation and mean. Standard deviation of n value is given by SD = √( Σ (xm - xi)² / n ), where the sum runs over i = 1 to n and xm is the mean of the values.

SD = √( Σ (xm − xi)² / n ), where xm is the mean. Two user defined functions are used: mean() and stdDev().

Pseudocode

FUNCTION mean(x[], n)
    sum <- 0
    FOR i <- 0 TO n-1
        sum <- sum + x[i]
    END FOR
    RETURN sum / n
END FUNCTION

FUNCTION stdDev(x[], n)
    xm <- mean(x, n)
    s <- 0
    FOR i <- 0 TO n-1
        s <- s + (xm - x[i]) * (xm - x[i])
    END FOR
    RETURN sqrt(s / n)
END FUNCTION

MAIN
    READ n
    FOR i <- 0 TO n-1
        READ x[i]
    END FOR
    m  <- mean(x, n)
    sd <- stdDev(x, n)
    PRINT "Mean =", m
    PRINT "Standard deviation =", sd
END

C version of the same logic (checked by running)

#include <stdio.h>
#include <math.h>

float mean(float x[], int n)
{
    float sum = 0;
    for (int i = 0; i < n; i++)
        sum += x[i];
    return sum / n;
}

float stdDev(float x[], int n)
{
    float xm = mean(x, n), s = 0;
    for (int i = 0; i < n; i++)
        s += (xm - x[i]) * (xm - x[i]);
    return sqrt(s / n);
}

int main(void)
{
    float x[100];
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    printf("Enter %d values: ", n);
    for (int i = 0; i < n; i++)
        scanf("%f", &x[i]);
    printf("Mean = %.3f\nStandard deviation = %.3f\n", mean(x, n), stdDev(x, n));
    return 0;
}

Sample run (values 2 4 4 4 5: mean = 3.8, Σ(xm − xi)² = 4.8, SD = √(4.8/5) = 0.980)

Input: 5 2 4 4 4 5

Enter n: Enter 5 values: Mean = 3.800
Standard deviation = 0.980

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →