Hi,
Please find below the code for an exercise I had to do as part of a course book I use to learn C.
The program is to accept input from an ASCII text file using redirection, count the number of occurrences of each character and output this info on to the screen.
I would appreciate any suggestions or comments about the code.
Look forward to hearing from anyone who would care or have the time for that sort of thing.
Code:/* ex14-7.c: Write a program that uses redirection to accept input from a disk file, counts the number of times each letter occurs in the file, and then displays the results on-screen */ #include <stdio.h> int main(void) { /* declare and initilise an array of type int to hold number of * occurences of each character being input. */ int input[25] = {0}; char input_c[25]; /* declare and initialise a variable of type int to hold ASCII * value of each character being input. */ int c = 0; int i; /* while loop to accept input */ while ((c=getchar()) != EOF) { /* switch block to sort out input */ switch(c) { case 'a': input_c[0] = c; ++input[0]; break; case 'b': input_c[1] = c; ++input[1]; break; case 'c': input_c[2] = c; ++input[2]; break; case 'd': input_c[3] = c; ++input[3]; break; case 'e': input_c[4] = c; ++input[4]; break; case 'f': input_c[5] = c; ++input[5]; break; case 'g': input_c[6] = c; ++input[6]; break; case 'h': input_c[7] = c; ++input[7]; break; case 'i': input_c[8] = c; ++input[8]; break; case 'j': input_c[9] = c; ++input[9]; break; case 'k': input_c[10] = c; ++input[10]; break; case 'l': input_c[11] = c; ++input[11]; break; case 'm': input_c[12] = c; ++input[12]; break; case 'n': input_c[13] = c; ++input[13]; break; case 'o': input_c[14] = c; ++input[14]; break; case 'p': input_c[15] = c; ++input[15]; break; case 'r': input_c[16] = c; ++input[16]; break; case 's': input_c[17] = c; ++input[17]; break; case 't': input_c[18] = c; ++input[18]; break; case 'u': input_c[19] = c; ++input[19]; break; case 'v': input_c[20] = c; ++input[20]; break; case 'w': input_c[21] = c; ++input[21]; break; case 'x': input_c[22] = c; ++input[22]; break; case 'y': input_c[23] = c; ++input[23]; break; case 'z': input_c[24] = c; ++input[24]; break; default: break; } } puts("Here's statistics on number of times each characer was encountered in your input:"); for (i=0; i<=25; i++) printf("%c was encountered %d times\n", input_c[i], input[i]); return 0; }