CS 200 - Lab 15

Character Histogram

Write a program to read arbitrary input from the user and count the number of occurrences of each letter.  When the user signals end of input (Control-Z followed by Enter), the program should display a histogram (bar graph) of the number of occurrences of each letter.

Example run (user input in bold red):

It is a truth universally acknowledged, that a single man in
possession of a good fortune, must be in want of a wife.
However little known the feelings or views of such a man may
be on his first entering a neighbourhood, this truth is so well
fixed in the minds of the surrounding families, that he is considered
the rightful property of some one or other of their daughters.
"My dear Mr. Bennet," said his lady to him one day, "have you
heard that Netherfield Park is let at last?"
Mr. Bennet replied that he had not.
Letter counts:
A: ============================
B: =====
C: ===
D: ==================
E: =================================================
F: ==============
G: =========
H: ============================
I: =================================
K: ===
L: ================
M: ===========
N: ==============================
O: ===============================
P: =====
R: ==========================
S: ===========================
T: ======================================
U: ============
V: ====
W: =======
X: =
Y: =======
The histogram shows that E was the most frequently-occurring letter, followed by T.

Getting started

If you have a solution open in Visual Studio, close it (File->Close Solution).

Download lab15.zip.  Import it into Visual Studio (File->Import...).

Add your code to the source file called Histogram.c.


Use the standard loop for processing the entire sequence of characters typed by the user:

while (!feof(stdin)) {
int ch;

ch = getchar();

if (ch >= 0) {
/* process one character */

Use an array of int variables to keep track of the number of occurrences of each letter.  The array should be indexed by the position in the alphabet of each letter.  I suggest using 0 as the position of A, 1 as the position of B, etc.  If you use this approach, then for any letter, you can convert between the letter's code and its alphabet position by adding or subtracting either 'A' or 'a' as appropriate.  For example:

int ch, pos;


if ((ch >= 'A') && (ch <= 'Z')) {
pos = ch - 'A';

printf("The alphabet position of %c is %i\n", ch, pos);

Your program should handle both upper-case and lower-case letters.  I.e., both A and a should be counted as the same letter.

The %c printf conversion specifier prints a character specified by an integer character code.  For example:

printf("%c\n", 'A'); /* prints A */

Contrast this with the %i conversion specifier, which prints the integer code:

printf("%i\n", 'A'); /* prints 65, which is the character code for A */