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 TNOCHAR 128  /* Total Number of characters is 128: 0 - 127 */

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

    int character[TNOCHAR];
    
    for(i=0;i<TNOCHAR;++i)
        character[i] = 0;
    
    while((c=getchar())!=EOF)
        ++character[c];

    for(i=0;i<TNOCHAR;++i)
    {
        putchar(i);
        
        for(j=0;j<character[i];++j)
            putchar('*');
        
        putchar('\n');
    }
return 0;
}

Run this

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.

Comments by Disqus