|
| 1 | +/* |
| 2 | + * Exercise 1-14. Write a program to print a histogram of the frequencies of |
| 3 | + * different characters in its input. |
| 4 | + * |
| 5 | + * By Faisal Saadatmand |
| 6 | + */ |
| 7 | + |
| 8 | +/* Vertical Histogram. See 1-14.c for a horizontal histogram implementation */ |
| 9 | + |
| 10 | +#include <stdio.h> |
| 11 | + |
| 12 | +#define SIZE 93 /* size of characters array */ |
| 13 | +#define SCALE 1 /* adjust to accommodate large input */ |
| 14 | + |
| 15 | +int main(void) |
| 16 | +{ |
| 17 | + int c, i, count, longestBar; |
| 18 | + int characters[SIZE]; |
| 19 | + |
| 20 | + /* initialize elements' values to 0 */ |
| 21 | + for (i = 0; i < SIZE; ++i) |
| 22 | + characters[i] = 0; |
| 23 | + |
| 24 | + count = 0; |
| 25 | + while ((c = getchar()) != EOF) |
| 26 | + /* match graphical characters only (ASCII table) */ |
| 27 | + if (c >= '!' && c <= '~') { |
| 28 | + ++characters[c - '!']; |
| 29 | + ++count; /* number of matched characters */ |
| 30 | + } |
| 31 | + |
| 32 | + if (!count) |
| 33 | + return -1; |
| 34 | + |
| 35 | + printf("\nVertical Histogram:\n"); |
| 36 | + |
| 37 | + /* find the longestBar */ |
| 38 | + longestBar = 0; |
| 39 | + for (i = 0; i < SIZE; ++i) |
| 40 | + if (characters[i] > longestBar) |
| 41 | + longestBar = characters[i]; |
| 42 | + longestBar /= SCALE; |
| 43 | + |
| 44 | + /* print vertical histogram */ |
| 45 | + while (longestBar > 0) { |
| 46 | + for (i = 0; i < SIZE; ++i) |
| 47 | + if (characters[i] != 0) { /* skip if no data */ |
| 48 | + if (characters[i] / SCALE < longestBar) |
| 49 | + printf(" %c", ' '); |
| 50 | + else |
| 51 | + printf(" %c", '*'); |
| 52 | + } |
| 53 | + printf("\n"); |
| 54 | + --longestBar; |
| 55 | + } |
| 56 | + |
| 57 | + /* print labels */ |
| 58 | + for (i = 0; i < SIZE; ++i) |
| 59 | + if (characters[i] != 0) /* skip if no data */ |
| 60 | + printf (" %c", i + '!'); |
| 61 | + printf("\n"); |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments