Exercise 1-13-1 (horizontal - Histogram of word lengths)

Chapter_1     Exercise_1-12     countc Exercise_1-13-2







Exercise 1-13     K&R, p. 24


Exercise 1-13. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.




histwh.c         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define MAXLENGTHS 1000 // max no of different word lengths
#define FALSE 0
#define TRUE 1

// histogram of lengths of words, horizontally

int main()
{
int c, i, j;
int wlengths[MAXLENGTHS]; // keep unsorted
int occurrences[MAXLENGTHS]; // match wlengths[]
int wl = 0; // current word length
int nwl = 0; // no of different word lengths
int newlength = FALSE; // new word length

for (i = 0; i < MAXLENGTHS; i++) // initialize
{occurrences[i] = wlengths[i] = 0;}

while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == '\v')
{
if (wl > 0) // new word
{
newlength = TRUE;
for (i = 0; i < nwl; i++)
{
if (wl == wlengths[i])
{
occurrences[i]++;
newlength = FALSE;
break; // out of for()
}
}
if (newlength == TRUE)
{
newlength = FALSE; // reset newlength
wlengths[nwl] = wl; // word length
occurrences[nwl]++; // occurrences[nwl] = 1;
nwl++; // array index starts at 0, initial value of nwl
}
wl = 0; // reset current word length
}
// else skip whitespace
}
else {wl++;} // not whitespace
}

printf("\t\tLEGEND:\n");
printf("Lengths:\t");
for (i = 0; i < nwl; i++) // print until wlengths[i] == 0
{printf("%d ",wlengths[i]);}
putchar('\n');
printf("Occurrences:\t");
for (i = 0; i < nwl; i++)
{printf("%d ",occurrences[i]);}
putchar('\n');

printf("\t\tHISTOGRAM:\n");
printf("Lengths:\tOccurrences:\n");
for (i = 0; i < nwl; i++)
{
printf("%8d\t",wlengths[i]); // 8 is the length of "Lengths:"
for (j = 0; j < occurrences[i]; j++)
{putchar('-');}
putchar('\n');
}
}
/*
gcc histwh.c -o histwh
./histwh < histwh.c // input source file
LEGEND:
Lengths: 8 9 7 10 4 2 3 5 1 6 12 21 24 11 15 17 13 19 16 14 25 27 35 28
Occurrences: 6 9 10 8 30 78 27 16 60 17 2 2 2 5 3 1 1 2 2 3 1 1 1 1
HISTOGRAM:
Lengths: Occurrences:
8 ------
9 ---------
7 ----------
10 --------
.................................

./histwh < histwh // input binary file
LEGEND:
Lengths: 56 240 7 174 103 24 282 19 67 123 23 270 15 168 2594 84 49 107 ...
Occurrences: 1 1 11 1 1 1 1 3 1 1 10 1 3 1 1 1 1 1 ...
HISTOGRAM:
Lengths: Occurrences:
56 -
240 -
7 -----------
174 -
103 -
24 -
282 -
19 ---
168 -
2594 -
84 -
..................................
*/









Chapter_1     Exercise_1-12     countc BACK_TO_TOP Exercise_1-13-2



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo