Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that will guess an integer that the user has picked. Imagine tha

ID: 3857461 • Letter: W

Question

Write a program that will guess an integer that the user has picked. Imagine that the user will write down a positive integer x on a piece of paper and your program will repeatedly ask questions in order to guess what x is, and the user replies honestly. Your program will start by asking for an int n, and you must have 1 lessthanorequalto x lessthanorequalto n. After that, the program will successively guess what x is, and the user must tell the computer if x is equal to the guess (entering 'e'), larger than the guess (entering 'l'), or smaller than the guess (entering 's'). Your program will guess by maintaining a lower bound (initially 1) and upper bound (initially n) and pick the largest integer equal to or smaller than^1 the midpoint of the lower bound and upper bound. If the user responds with 'l' indicating that x is larger the guess becomes the new lower bound plus one. If the user responds with 's' indicating that x is smaller, the guess becomes the new upper bound minus one. If the user responds with 'e' indicating that x is the guess, your program will report the number of guesses made and terminate execution: [rsgyse1@pc17] $ /guessyournumber Enter n: 50 Is your number 25? l Is your number 38? l Is your number 44? s Is your number 41? e Your number must be 41. I used 4 guesses. If the user responds in a way that is not feasible (no such x can exist), print an error and quit: [rsgyse10pc17] $ /guessyournumber Enter n: 9 Is your number 4? s

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
void clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != ' ' && c != EOF);
}
void main()
{
int n;
int low,mid,high;
int count=0;
char choice='a';
printf("Enter n:");

scanf("%d",&n);
clean_stdin();
low=0,high=n;
while(1){
count++;
mid=(low+high)/2;
printf("Is your number %d?",mid);
  
scanf("%c",&choice);
clean_stdin();
  
if(choice=='e')
{
printf("your number must be %d.I used %d guesses",mid,count);
break;
}
else if(choice=='l')
{
low=mid+1;
}
else
{
high=mid-1;
}
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote