about summary refs log tree commit diff stats
path: root/1.6.c
blob: 95b8841b8f16697b1c32b4dbff69fdfef655fbb2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>

#define NASCII ('~' - '!')

int longest(const int *list, const int length) {
    int max = 0;
    for (int i = 0; i < length; i++){
        if (list[i] > max) max = list[i];
    }
    return max;
}

void usage() {
    fprintf(stderr, "print a histogram of the frequencies of \
ascii characters in stdin (K&R ex 1-14)\n");
    fprintf(stderr, "    vertical axis is frequency\n");
    fprintf(stderr, "    horizontal axis is character\n");
}

int main (int argc, char *argv[]) {
    if (argc > 1) { usage(); return 0;}
	int c, i, j;
	int ascii[NASCII] = {0};

	while ((c = getchar()) != EOF) {
		if (c >= '!' && c <= '~') {
			++ascii[c - '!'];
        }
    }
    int max = longest(ascii, NASCII);
    // i counts down from the top to the bottom
    // (actually from a couple above the top, for padding)
    // we start printing each bar as i gets to be within the bar's value
	for (i = max + 2; i > 0; i--) {
        // side axis
		printf("%4d |", i);
        for (int j = 0; j < NASCII; ++j)
            printf("%s", i <= ascii[j] ? "\u2588" : " ");
        printf("\n");
    }
    // bottom axis
    printf("     +");
    for (j = '!'; j <= '~'; ++j)
        printf("-");
    // bottom labels
    printf("\n     |");
    for (j = '!'; j <= '~'; ++j)
        printf("%c", j);
    printf("\n");
    return 0;
}