Completed and improved ex1_10 using a switch function.

This commit is contained in:
Reina Harrington-Affine 2025-08-14 19:23:28 +00:00
parent d3262419a8
commit d6f81778ef

30
KNR C/ex1_10_improved.c Normal file
View file

@ -0,0 +1,30 @@
#include <stdio.h>
/*Alternative (challenge) implementation of exercise 1-10 using a switch statement
* as opposed to a series of if statements*/
int main(){
int a = 0; /*Initializing a as zero; this doesn't matter because getchar is called at the top of the loop */
while (a != EOF){
a = getchar();
switch (a){
case '\t':
printf ("\\t");
break;
case '\\':
printf ("\\\\");
break;
case '\b':
printf ("\\b");
break;
case EOF: /*Required case for checking if a is EOF, since the loop actually tests whether a = EOF before refreshing a, thus allowing us to enter the loop with the value of a set to EOF */
break;
default:
putchar (a);
}
}
return 0;
}