runner$ cat freq_struct2.c /* Calculate fequencies of letters in an input file */ #include #include struct table_tag { char letter; int count; }; void bubble(struct table_tag table[]); void swap(struct table_tag *table1, struct table_tag *table2); void printfreq(struct table_tag table[], int tot); void main(void) { struct table_tag table[26]; int i; /* index for lc array */ int tot = 0; /* total number of alpha characters */ int ch; /* int so that EOF will work */ for (i = 0; i < 26; i++) { table[i].letter = (char) (i + 'a'); table[i].count = 0; } while ((ch = getchar()) != EOF) if (isalpha(ch = tolower(ch))) { tot++; table[ch - 'a'].count++; } bubble(table); printfreq(table, tot); } /* bubble: sort lc array into decreasing order. Carry alf along */ void bubble(struct table_tag table[]) { int i, dum; for (dum = 0; dum < 25; dum++) for (i = 0; i < 25; i++) if (table[i].count < table[i+1].count) swap(&table[i], &table[i+1]); } void swap(struct table_tag *table1, struct table_tag *table2) { struct table_tag temp; temp = *table1; *table1 = *table2; *table2 = temp; } /* printfreq: print out the frequency table */ void printfreq(struct table_tag table[], int tot) { int i; printf("Frequency count of letters, out of total: %d\n\n", tot); printf(" Letter Frequency (%%)\n"); for (i = 0; i < 26; i++) printf("%6c %13.3f%%\n", table[i].letter, (double)table[i].count/tot*100.0); } runner$ freq_struct2 AaAaA bbbBBbbbbb ZzZzZZZzzZzzzzz (ctrl-D) Frequency count of letters, out of total: 30 Letter Frequency (%) z 50.000% b 33.333% a 16.667%