Last active
June 1, 2017 18:25
-
-
Save barthr/8b1e4a0c7c129b6a0a99b6e3441b5299 to your computer and use it in GitHub Desktop.
Wordcount with histogram written in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAXWORDLEN 20 // Maximum length of a word | |
#define IN 1 // Inside a word | |
#define OUT 0 // Outside a word | |
int main(void) | |
{ | |
int c; | |
int words[MAXWORDLEN] = {0}; | |
int longest_word = 0; | |
int wordcount = 0; | |
int state = OUT; | |
while ((c = getchar()) != EOF) | |
{ | |
if (c == ' ' || c == '\n' || c == '\t') | |
{ | |
if (state == IN && wordcount <= MAXWORDLEN) | |
{ | |
words[wordcount]++; | |
longest_word = (words[wordcount] > longest_word) ? words[wordcount] : longest_word; | |
} | |
state = OUT; | |
} | |
else | |
{ | |
if (state == OUT) | |
{ | |
wordcount = 0; | |
state = IN; | |
} | |
++wordcount; | |
} | |
} | |
for (int i = longest_word; i >= 1; i--) | |
{ | |
for (int j = 0; j < MAXWORDLEN; j++) | |
{ | |
if (words[j] >= i) | |
{ | |
printf(" *"); | |
} | |
else | |
{ | |
printf(" "); | |
} | |
} | |
printf("\n"); | |
} | |
for (int i = 0; i < MAXWORDLEN; i++) | |
printf("---"); | |
printf("\n"); | |
for (int i = 0; i < MAXWORDLEN; i++) | |
printf("%3d", i); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment