BootCamp2012: letters.2.c

File letters.2.c, 1.2 KB (added by mmc, 12 years ago)

Solution for Assignment #5

Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <ctype.h>
4
5#define NLETTERS 26
6
7int
8main(int argc, char **argv)
9{
10    int wordb = -1;         /* word search state: -1 = starting
11                             *                     0 = found space
12                             *                     1 = found word */
13    int nwords = 0;         /* count the number of words */
14    int count[NLETTERS];    /* counts for all letters being tracked */
15    int i, c;
16
17    /* zero out all counts */
18    for (i=0; i < NLETTERS; i++) {
19        count[i] = 0;
20    }
21
22    printf("Type in a sentence:\n");
23    c = getchar();
24    while (c != '\n') {
25        if (isspace(c)) {
26            wordb = 0;
27        } else if (isalpha(c)) {
28            if (wordb != 1) {
29                nwords++;
30                wordb = 1;
31            }
32        }
33
34        c = tolower(c) - 'a';
35        if (c >= 0 && c < NLETTERS) {
36            count[c]++;
37        }
38
39        c = getchar();
40    }
41
42    /* print out results */
43    printf("Statistics:\n");
44    printf("%d words\n\n", nwords);
45    for (i=0; i < NLETTERS; i++) {
46        if (count[i] > 0) {
47            printf("Letter %c: %d\n", i+'a', count[i]);
48        }
49    }
50    return 0;
51}