Exercise 1.14 - Histogram of Frequency of Characters

Question

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

Solution

/**
 *
 * Histogram of Frequency of Different Characters in Input
 *
 **/

#include <stdio.h>

#define TOTAL_CHARS 128 /* Total Number of characters is 128: 0 - 127 */

int main(void) {
    int c, i, j;

    int _char[TOTAL_CHARS];

    for (i = 0; i < TOTAL_CHARS; ++i) {
        _char[i] = 0;
    }

    while ((c = getchar()) != EOF) {
        _char[c] = _char[c] + 1;
    }

    for (i = 0; i < TOTAL_CHARS; ++i) {
        putchar(i);

        for (j = 0; j < _char[i]; ++j)
            putchar('*');

        putchar('\n');
    }
    return 0;
}

Explanation

We define a label TNOCHAR 128 for total number of printable characters in ascii tabel (0 to 127) and we create an array ` int character[TNOCHAR]` to hold the number of occurances of those characters. As we get each character from the input, we increment it’s count in the character array.

We print the histogram at the end, by looping through the characters of the array, printing the character and then printing * for number of times that character had occurred.