about summary refs log blame commit diff stats
path: root/1.6.c
blob: 95b8841b8f16697b1c32b4dbff69fdfef655fbb2 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
                  
 
                          
 
                                                
                





                                         
              



                                                              



                                       

                                
 
                                        

                                           

         
                                     




                                                                        
                                   
                                        
                                                         
                     
     
                  
                     


                                
                       

                                
                 
             
 
#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;
}