Exercise 1-14

Write a program to print a histogram of the frequencies of different characters in its input.

The first thing we do is store each character's frequency in an array called freq. We can take advantage of the fact that a char is really just a numeric value and use the character itself as the index for its frequency (e.g. we store the frequency of the character 'a' in freq['a'].)

    #include <stdio.h>
    
    #define SIZE 128    /* number of chars in the ASCII char set */
    
    main()
    {
        int c, i;
        int freq[SIZE]; /* frequencies of characters */
    
        for (i = 0; i < SIZE; ++i)
            freq[i] = 0;
        while ((c = getchar()) != EOF)
            ++freq[c];
    }

To print the histogram, we have to iterate through freq using a for-loop; if a frequency is greater than zero, we print the character followed by another for-loop that prints the number of dashes that corresponds with the character's frequency. If the character is invisible, we print its escape sequence instead.

    #include <stdio.h>
    
    #define SIZE 128    /* number of chars in the ASCII char set */
    
    main()
    {
        int c, i, j;
        int freq[SIZE]; /* frequencies of characters */
    
        for (i = 0; i < SIZE; ++i)
            freq[i] = 0;
        while ((c = getchar()) != EOF)
            ++freq[c];
        /* print the histogram */
        for (i = 0; i < SIZE; ++i) {
            if (freq[i] > 0) {
                if (i == ' ')
                    printf("\\ : ");
                else if (i == '\n')
                    printf("\\n: ");
                else if (i == '\t')
                    printf("\\t: ");
                else if (i == '\\')
                    printf("\\\\: ");
                else
                    printf("%2c: ", i);
                for (j = 0; j < freq[i]; ++j)
                    putchar('-');
                putchar('\n');
            }
        }
    }

Note: we use %2c because escape sequences are two characters long. Doing this ensures the bars align regardless of whether invisible characters are entered or not.