Skip to content

Instantly share code, notes, and snippets.

@barthr
Last active June 1, 2017 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barthr/8b1e4a0c7c129b6a0a99b6e3441b5299 to your computer and use it in GitHub Desktop.
Save barthr/8b1e4a0c7c129b6a0a99b6e3441b5299 to your computer and use it in GitHub Desktop.
Wordcount with histogram written in C
#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