In: Computer Science
The following code snippet is free of errors (issues that will prevent the code from compiling) but it does contain a major bug that will cause the program to hang (not finish running). Identify the problem and create a line of code to fix it.
#include <stdio.h> char get_input(); int main() { printf("The user's inputted letter is %c\n", get_input()); return 0; } char get_input() { printf("Please enter a letter: \n"); char input = getchar(); while (!(input >= 'a' && input <= 'z') && !(input >= 'A' && input <= 'Z')) { printf("You did not enter a letter! Try again\n"); } return input; }
Answer
Here is your answer, if you have any doubt please comment, i am here to help you.
here is your fix for the above problem.
ERROR
while (!(input >= 'a' && input <= 'z') && !(input >= 'A' && input <= 'Z')) {
printf("You did not enter a letter! Try again\n");
}
/*there is no exit for the above while loop, any while loop or for loop there must be a terminate statement.
Here you don't need while loop, just only enough if statement.
If your are using while just add break after printf()*/
FIX
#include <stdio.h>
char get_input();
int main() {
printf("The user's inputted letter is %c\n", get_input());
return 0;
}
char get_input() {
printf("Please enter a letter: \n");
char input = getchar();
//just change while loop to if, then not use break
while (!(input >= 'a' && input <= 'z') && !(input >= 'A' && input <= 'Z')) {
printf("You did not enter a letter! Try again\n");
//break; //use break if while loop using,
}
return input;
}
output
Any doubt please comment,
Thanks in advance