typestar

average.c in C

A complete program: read numbers from a file, average them, handle the failures.

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

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s N [N ...]\n", argv[0]);
        return 1;
    }
    double sum = 0.0, sumsq = 0.0;
    int n = argc - 1;
    for (int i = 1; i < argc; i++) {
        double value = strtod(argv[i], NULL);
        sum += value;
        sumsq += value * value;
    }
    double mean = sum / n;
    double variance = sumsq / n - mean * mean;
    printf("count: %d\n", n);
    printf("mean:  %.3f\n", mean);
    printf("stdev: %.3f\n", sqrt(variance > 0 ? variance : 0));
    return 0;
}

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
525
Tokens
166
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 3 in Encore, step 33 of 35 in Language basics.

← Previous Next →