From 22694dfae0b60d771c5c7fef45fe94e7ab275486 Mon Sep 17 00:00:00 2001 From: Reina Harrington-Affine Date: Tue, 26 Aug 2025 17:42:41 +0000 Subject: [PATCH] Added support for numbers. Removed refTable[], changed enumeration loop to check via sequential if-else statements if a character is within a given range. This was done in favor of a lookup array to improve performance. --- KNR C/ex1_14_improved.c | 63 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 KNR C/ex1_14_improved.c diff --git a/KNR C/ex1_14_improved.c b/KNR C/ex1_14_improved.c new file mode 100644 index 0000000..e6520ac --- /dev/null +++ b/KNR C/ex1_14_improved.c @@ -0,0 +1,63 @@ +#include + +/*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; +}