Problem Statement:
Exercise 1-14: Write a program to print a histogram of the frequencies of different characters in its input.Solution:
Problem is similar to K & R : Exercise 1.13 - Vertical histogram [Part 2]. The printable characters in ASCII table is from 33 to 126.Here is solution
#include <stdio.h> #define MAX_WORD_LEN 94 int main() { int count[MAX_WORD_LEN] = {0}; int c, len = 0, max = 0; int i = 0, j = 0; while((c = getchar()) != EOF) { if(c >= 33 && c <= 126) { count[c-33]++; if(count[c-33] > max) { max = count[c-33]; } } } printf("\n"); /* Draws the histogram */ for(i = max; i >= 1; i--) { for(j = 1; j <= MAX_WORD_LEN; j++) { if(count[j] > i) { printf("*"); }else { printf(" "); } } printf("\n"); } /* Draws a verticle line */ for(j = 1; j <= MAX_WORD_LEN; j++) { printf("-"); } printf("\n"); /* Print the counts */ for(j = 1; j <= MAX_WORD_LEN; j++) { printf("%c", j+33); } printf("\n"); return 0; }
Next Article - K & R : Exercise 1.15 - Temperature conversion function
Previous Article - K & R : Exercise 1.13 - Vertical histogram [Part 2]
All Article - K & R Answers
No comments :
Post a Comment