Skip to content

Instantly share code, notes, and snippets.

@gulan
Created November 17, 2016 18:01
Show Gist options
  • Select an option

  • Save gulan/c6d6501b8bb86c26f6724cc570ea85db to your computer and use it in GitHub Desktop.

Select an option

Save gulan/c6d6501b8bb86c26f6724cc570ea85db to your computer and use it in GitHub Desktop.
/* Exercise 1-13. Write a program to print a histogram of the lengths
of words in its input. */
/*
input = (special | word)*
special = blank | tab | newline
word = non-special+
*/
#include<stdio.h>
#define N 64
int
main(int argc, char argv[]) {
int ch;
int wordlen;
int b[N];
int i,j,last;
char buf[N];
for (i=0; i<N; i++) {
b[i] = 0;
}
ch = getchar();
while (ch != EOF) {
switch (ch) {
case ' ':
case '\t':
case '\n':
ch = getchar();
break;
default:
wordlen = 0;
for (i=0; i<N; i++) {
buf[i] = 0;
}
i = 0;
while (ch != EOF && ch != ' ' && ch != '\t' && ch != '\n') {
wordlen++;
buf[i++] = ch;
ch = getchar();
}
b[wordlen]++;
buf[i] = 0;
}
}
/* find the last non-zero entry */
last = N-1;
while (last>=0 && b[last]==0) {
last--;
}
/* print histogram without scaling */
for (i=1; i<last+1; i++) {
for (j=0; j<b[i]; j++) {
putchar('*');
}
putchar('\n');
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment