K&R Solutions - 1.14

Q: Write a program to print a histogram of the frequencies of different characters in its input.

A:

#include <stdio.h>

int main(void) 
{
  int FREQUENCY_LENGTH = 256; // We'll just count all ASCII values. Why not?
  int frequencies[FREQUENCY_LENGTH];
  int i, j, c;
  int tally = 0;

  for (i = 0; i < FREQUENCY_LENGTH; ++i) {
    frequencies[i] = 0;
  }

  // This part gets a lot more simple.
  while ((c = getchar()) != EOF) {
    ++frequencies[c];
  }

  printf("\n");
  printf("Character Frequencies\n");
  printf("---------------------\n");
  /* For the sake of brevity, we will only print visible characters.
   * The ASCII values for visible characters are all between 33 and 126,
   * a fact I pulled off www.asciitable.com
   */
  for (i = 33; i <= 126; ++i) {
    printf("%c | ", i);

    for (j = 0; j < frequencies[i]; ++j) {
      printf("-");
    }

    printf("\n");
  }

  return 0;
}
America! Land of my dreams, home of the Whopper!

(ctrl+d)

Character Frequencies
---------------------
! | --
" | 
# | 
$ | 
% | 
& | 
' | 
( | 
) | 
* | 
+ | 
, | -
- | 
. | 
/ | 
0 | 
1 | 
2 | 
3 | 
4 | 
5 | 
6 | 
7 | 
8 | 
9 | 
: | 
; | 
< | 
= | 
> | 
? | 
@ | 
A | -
B | 
C | 
D | 
E | 
F | 
G | 
H | 
I | 
J | 
K | 
L | -
M | 
N | 
O | 
P | 
Q | 
R | 
S | 
T | 
U | 
V | 
W | -
X | 
Y | 
Z | 
[ | 
\ | 
] | 
^ | 
_ | 
` | 
a | ---
b | 
c | -
d | --
e | -----
f | --
g | 
h | ---
i | -
j | 
k | 
l | 
m | ----
n | -
o | ----
p | --
q | 
r | ---
s | -
t | -
u | 
v | 
w | 
x | 
y | -
z | 
{ | 
| | 
} | 
~ |