Page 372 - Programming Microcontrollers in C
P. 372
Coding the Alpha Data 357
sorted is contained in an array of structures. The structure is
typedefed and called a type Entry. Each instance of an Entry
contains an integer value count and a character named letter. The
letter is the actual letter being recorded and count is the number
of occurrences of the letter in a document.
Our alphabet consists of the normal 26 letters plus the space and
new line characters. Therefore the constant LETTERS is given a
value of 28.
In the main program, the necessary variables are defined. Note
that the array of Entrys named letters[] contains LETTERS
entries. The variables used to count the input data are initialized. The
variable characters is initialized to zero. The character member
of the array letters is initialized to the actual character values in
order and the count value is initialized to zero. The character values
in the last two entries in the array are initialized to ‘>’ and ‘<’ respec
tively to correspond to the space character and the new line character.
When reading the data in, each character is operated on by the
tolower() function. This operation converts any upper-case letter to
a lower-case letter, but it does not alter any other characters. If the
character returned is a letter, a space or a new line character, it will be
processed by the following block. Otherwise, the character is discarded
and a new character is read in by the argument of the while() loop.
As the characters to be processed are detected, the corresponding
letters.count is incremented in the array. After all of the data are
entered, an EOF is detected, the data are sorted and then printed out.
The modifications to the earlier shell sort are minimal. First of
all, the array passed to the routine is identified as a type Entry
rather than an int. Also, the temp variable is a type Entry. Then
the comparison in the test argument of the innermost for() loop is
converted to compare the two v[].count entries. The swap
operation that follows needs no modification.
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define LETTERS 28
typedef struct{