/* Write a program to print a histogram of the lengths of words on its input. It's easy-to-draw the histogram with the bars horizontal; A vertical orientation is more challenging. */#include <stdio.h> #define MAXHIST/* max length of histogram */#define MAXWORD/* max length of a word */#define IN 1/* inside a word */#define OUT 0/* Outside a word *//* print horizontal histogram */main () {int C, I, NC, State;int Len; /* length of each bar */int MaxValue; /* Maximum value for wl[] */int Ovflow; /* Number of overflow words */int Wl[maxword]; /* Word length counters */state = OUT;NC = 0; /* Number of chars in a word */ovflow = 0; /* Number of words >= maxword */for (i = 0; i < Maxword; ++i) {wl[i] = 0;} while ((c = GetChar ()) = EOF) {if (c = = ' | | c = = ' \ n ' | | c = = ' \ t ') {state = out;if (NC > 0) {if (NC < Maxword) {++WL[NC ];} Else{++ovflow;}} NC = 0;} else if (state = = off) {state = IN;NC = 1; /* Beginning of a New word */}else{++nc; /* inside a word */}}maxvalue = 0;for (i = 1; i < Maxword; ++i) {if (Wl[i] > MaxValue) {maxvalue = Wl[i];}} for (i = 1; i < Maxword; ++i) {printf ("%5d-%5d:", I, wl[i]), if (Wl[i] > 0) {if (len = wl[i] * maxhist/maxvalue) &L t;= 0) {len = 1;} Else{len = 0;}} while (Len > 0) {putchar (' * ');--len;} Putchar (' \ n ');} if (Ovflow > 0) {printf ("There is%d words >=%d\n", Ovflow, Maxword);}}
/* Write a program to print a histogram of the lengths of words on its input. It's easy-to-draw the histogram with the bars horizontal; A vertical orientation is more challenging. */#include <stdio.h> #define MAXHIST/* max length of histogram */#define MAXWORD/* max length of a word */#define IN 1/* inside a word */#define OUT 0/* Outside a word *//* print vertical histogram */main () {int C, I, J, NC, State;int MaxValue; /* Maximum value for wl[] */int Ovflow; /* Number of overflow words */int Wl[maxword]; /* Word length counters */state = OUT;NC = 0; /* Number of chars in a word */ovflow = 0; /* Number of words >= maxword */for (i = 0; i < Maxword; ++i) {wl[i] = 0;} while ((c = GetChar ()) = EOF) {if (c = = ' | | c = = ' \ n ' | | c = = ' \ t ') {state = out;if (NC > 0) {if (NC < Maxword) {++WL[NC ];} Else{++ovflow;}} NC = 0;} else if (state = = off) {state = IN;NC = 1; /* Beginning of a new word */}else{++nc; /* Inside a WOrd */}}maxvalue = 0;for (i = 1; i < Maxword; ++i) {if (Wl[i] > MaxValue) {maxvalue = Wl[i];}} for (i = maxhist; i > 0; i.) {for (j = 1; j < Maxword; ++j) {if (wl[j] * Maxhist/maxvalue >= i) {printf ("*");} else{printf ("");}} Putchar (' \ n ');} for (i = 1; i < Maxword; ++i) {printf ("%4d", I);} Putchar (' \ n '); for (i = 1; i < Maxword; ++i) {printf ("%4d", Wl[i]);} Putchar (' \ n '), if (Ovflow > 0) {printf ("There is%d words >=%d\n", Ovflow, Maxword);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C-the C Answer (2nd Edition)-Exercise 1-13