Skip to content

Instantly share code, notes, and snippets.

@sqroot3
Last active April 15, 2018 18:49
Show Gist options
  • Save sqroot3/7fface991c172c135512c1cbd7ccfa40 to your computer and use it in GitHub Desktop.
Save sqroot3/7fface991c172c135512c1cbd7ccfa40 to your computer and use it in GitHub Desktop.
charcount.c - prints histogram of frequencies of different characters in input (only printing visible ones)
#include <stdio.h>
/*
Author: Matias Lago
Objective: Print histogram of frequencies of different characters in input (will only print visible ones)
*/
#define STARTING_CHARACTER ' '
#define ENDING_CHARACTER '~'
int main()
{
int c;
int characters[(ENDING_CHARACTER - STARTING_CHARACTER) + 1];
for(int i=STARTING_CHARACTER; i <= ENDING_CHARACTER; ++i)
characters[i - STARTING_CHARACTER] = 0;
while((c = getchar()) != EOF) {
++characters[c - STARTING_CHARACTER];
}
for(int i=STARTING_CHARACTER; i <= ENDING_CHARACTER; ++i) {
printf("%d (%c): ", i, i);
for(int j=0; j < characters[i - STARTING_CHARACTER]; ++j)
putchar('-');
putchar('\n');
}
}
@sqroot3
Copy link
Author

sqroot3 commented Apr 15, 2018

Works well when:

  • Same starting and ending character
  • No input
  • Ending Character > Starting Character (negative array size error)
  • Adapts well to specific Ranges (i.e digits only, uppercase only, etc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment