runner% cat freq_typedef.c /* Calculate fequencies of letters in an input file */ #include #include typedef struct { char letter; int count; } table_type; void bubble(table_type table[]); void swap(table_type *table1, table_type *table2); void printfreq(table_type table[], int tot); void main(void) { table_type 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(table_type 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(table_type *table1, table_type *table2) { table_type temp; temp = *table1; *table1 = *table2; *table2 = temp; } /* printfreq: print out the frequency table */ void printfreq(table_type table[], int tot) { int i; printf("Frequency 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_typedef AaAaA bbbBBbbbbb ZzZzZZZzzZzzzzz (ctrl-D) Frequency of letters, out of total: 30 Letter Frequency (%) z 50.000% b 33.333% a 16.667% c 0.000% d 0.000% e 0.000% f 0.000% ... runner% cat freq_simp.c /* Calculate fequencies of letters in an input file */ #include #include char letter[26]; int count[26]; /* bubble: sort lc array into decreasing order. */ void bubble(void) { int i, dum; for (dum = 0; dum < 25; dum++) for (i = 0; i < 25; i++) if (count[i] < count[i+1]) { int temp = count[i]; char tempc = letter[i]; count[i] = count[i+1]; letter[i] = letter[i+1]; count[i+1] = temp; letter[i+1] = tempc; } } /* printfreq: print out the frequency table */ void printfreq(int tot) { int i; printf("Frequency of letters, out of total: %d\n\n", tot); printf(" Letter Frequency (%%)\n"); for (i = 0; i < 26; i++) printf("%6c %13.3f%%\n", letter[i], (double)count[i]/tot*100.0); } void main(void) { 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++) { letter[i] = (char) (i + 'a'); count[i] = 0; } while ((ch = getchar()) != EOF) if (isalpha(ch = tolower(ch))) { tot++; count[ch - 'a']++; } bubble(); printfreq(tot); } runner% freq_simp AaAaA bbbBBbbbbb ZzZzZZZzzZzzzzz (ctrl-D) Frequency of letters, out of total: 30 Letter Frequency (%) z 50.000% b 33.333% a 16.667% c 0.000% d 0.000% e 0.000% f 0.000% ...