LearnFrenzy
Sign in Take a free test

C Library Functions · Library Function Programs · Question 2

Mean, median and standard deviation with qsort and sqrt in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

For a list of test scores, print the mean, the median (sort with qsort) and the population standard deviation (sqrt).

Solution
main.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

static int cmp(const void *a, const void *b) {
    double x = *(const double *) a, y = *(const double *) b;
    return (x > y) - (x < y);
}

int main(void) {
    double s[] = {72, 95, 61, 88, 79, 84};
    size_t n = sizeof s / sizeof s[0];
    double sum = 0;
    for (size_t i = 0; i < n; i++)
        sum += s[i];
    double mean = sum / n;

    qsort(s, n, sizeof s[0], cmp);
    double median = n % 2 ? s[n / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;

    double var = 0;
    for (size_t i = 0; i < n; i++)
        var += pow(s[i] - mean, 2);
    printf("mean %.2f, median %.1f, std dev %.2f\n", mean, median, sqrt(var / n));
    return 0;
}

Output Verified by compiling and running

mean 79.83, median 81.5, std dev 11.04

The median needs sorted data: with an even count it is the average of the two middle values. The standard deviation is the square root of the mean squared distance from the mean.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links