Project-Scylla/KNR C/ex1_14_improved.c

64 lines
2.1 KiB
C
Raw Normal View History

#include <stdio.h>
/*Initial implementation of KNR C Exercise 1-14*/
int main(){
/*Initialize an array of labels for the numerical table later. This looks
* wierd since it's mostly refTable[] again, but again, we do this at
* copile rather than procedurally in order to avoid adding an extra if
* statement on the print loop to look for the specific case where i is
* 0 or 27 and print a different character that isn't in refTable*/
/*TODO find a way to do this so that # and ! are replaced by WSPC and PCTN
* respectively*/
int printTable [38] = { '#' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f', 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n', 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' ,
'v' , 'w' , 'x' , 'y' , 'z' , '!', '0' , '1'
, '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9'};
/*Initialize character count storage array. Whitespaces are stored at pos 0
* while letters are stored at their numeric positions in the alphabet, and
* punchtuation is stored at position 27.Numbers are stored at positions
* 28 through 38*/
int charCount[38] = { 0 };
int i = 0;
/*Begin input text enumeration loop...*/
for(int a = getchar(); a != EOF; a = getchar()){
/*Begin whitespace filter check*/
if(a == '\n' || a == ' ' || a == '\t'){
++ charCount[0];
continue; /*Escape and restart loop to avoid running redundant
tests.*/
} else if(a >= 97 && a <= 122) { /*Check for lowercase letters*/
++charCount[a - 96];
} else if(a >= 65 && a <= 90) { /*Check for uppercase letters*/
++charCount[a - 64];
} else if(a >= 48 && a <= 57) { /*Check for numbers*/
++charCount[a - 20];
}
}
/*Input text enumeration complete; set values in refTable for printing...*/
/*Begin output generation...*/
/*Vertical table of numerical values:*/
for(int i=0; i <= 27; ++i)
printf("%4c %4d\n", printTable[i], charCount[i]);
/*Print a histogram of gathered data (recycled from ex1_13_improved.c.*/
i = 0;
printf("\nHistogram of letters encountered.\n");
for (int b = charCount[i]; i <= 37; ++i){
printf ("%1c ", printTable[i]);
for (; b > 0; --b){
printf("|");
}
printf("\n");
b = charCount[(i + 1)];
}
return 0;
}