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