#include #include /* Guessing Game (15 points) Write a complete C program that asks the user to enter an integer number between 1 and 100. The program then tries to guess that number. After every guess the user must answer Yes (if the guess was correct), Higher (if the next guess should be higher), or Lower (if the next guess should be lower). The letters Y,H,L are used as shortcuts. If the user's answers are always truthful, then the program will eventually guess the number. If the user's answers are not truthful, then the program should detect that and print "You lied to me!" Try to optimize your program so that it does not exhaustively try to guess all possible numbers. Instead, it should use the higher/lower answers to restrict the range of possible remaining numbers. Note: even though the program "knows" what number the user entered (it is stored in a variable after all) it should not use the value of that variable in the guessing algorithm. The only reason the program reads this number is so that the user can better keep track of his answers. ============= START OF SAMPLE RUN ======================= Enter a number between 1 and 100: 70 Is your number equal to 50.? Please answer Higher, Lower, or Yes [H|L|Y]: h Is your number equal to 75? Please answer Higher, Lower, or Yes [H|L|Y]: l Is your number equal to 62? Please answer Higher, Lower, or Yes [H|L|Y]: h Is your number equal to 68? Please answer Higher, Lower, or Yes [H|L|Y]: h Is your number equal to 71? Please answer Higher, Lower, or Yes [H|L|Y]: l Is your number equal to 69? Please answer Higher, Lower, or Yes [H|L|Y]: h Is your number equal to 70? Please answer Higher, Lower, or Yes [H|L|Y]: y I guessed it correctly! ============= END OF SAMPLE RUN ======================= */ #define MAX 100 int main() { int N, guess, low, high, done; char answer; do { printf("Enter a number between 1 and %d: ", MAX); scanf(" %d", &N); }while((N<1) || (N > MAX)); low=1; // initialize some variables that are used below high=MAX; done = 0; do { if(low>high) { printf("You lied to me!\n\n"); break; } else guess = (low+high)/2; printf("Is your number equal to %d?\n", guess); printf("Please answer Higher, Lower, or Yes [H|L|Y]: "); scanf(" %c", &answer); switch(answer) { case 'y': // the guess was correct case 'Y': printf("I guessed it correctly!\n\n"); done=1; break; case 'h': // the guess was low, next one must be higher case 'H': low=guess+1; break; case 'l': // the guess was high, next one must be lower case 'L': high = guess-1; break; default: printf("Invalid input '%c'.\n", answer); break; } }while(!done); system("pause"); }