In: Computer Science
*C PROGRAMMING*
Create a program which requires the computer to guess the user's number from 1-100. The user does not need to enter their number at any point. The computer should just guess a random number, and then the user can choose whether or not the number is too high or too low, and if the computer does not guess the correct number, it will will keep guessing and eliminate the values from the range that is either too high or too low (depending on the user's selection after a guess is made).
EXAMPLE OF PROGRAM LOGIC:
num = 38 (user's selection - not actual input) 1 to 100 (high and low variables initialized) computer guess 50 (guess determined by 1 + 100 / 2) high (user says the number is too high) 49 (new high value - if high subtract 1 from guess and store in high) computer guess 25 (guess determined by 1 + 49 / 2) low (user) 26 (new low value - if low add 1 to guess and store in low) computer guess 38 (guess determined by 26 + 50 / 2) Correct! (user)
#include <stdio.h>
int main()
{
char ch;
int num,low=1,high=100,mid,f=0;
printf("High and low variables initialized\n");
while(low<high&&f==0)
{
mid=(low+high)/2;
printf("Computer Guess is %d\nenter h-high l-low
c-correct:\n",mid);
scanf(" %c",&ch);//enter character based on guessed number
high,low,or equal
if(ch=='h')
{
high=mid-1;//If guessed value is high make high=mid-1
printf("high=%d\n",high);
}
else if(ch=='l')//if guessed number is low
{
low=mid+1;//make low to mid +1
printf("Low=%d\n",low);
}
else if(ch=='c')
{
f=1;//if it is correct break from it
num=mid;
break;
}
}
if(f==1)
printf("The number is %d",num);
else
printf("You didn't guessed right number");
return 0;
}