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

Consider the classic number guessing game we played in class, where one person t

ID: 3761634 • Letter: C

Question

Consider the classic number guessing game we played in class, where one person thinks of a number and the second player attempts to guess that number given a number of attempts. For this exercise, you will write a program where the user will think of a number between 1 and 100, and the computer will attempt to guess it using the binary search algorithm. Sample output:

Think of a number between 1 and 100. Ready? (Y/N) Y

Is the number 50? (1=Higher, 2=Lower, 3=Exact) 2 Is the number 25? (1=Higher, 2=Lower, 3=Exact) 1

Is the number 37? (1=Higher, 2=Lower, 3=Exact) 3

Thanks for playing.

done by c++

Explanation / Answer

#include <iostream>
using namespace std;
void rangeH(int &mid, int &lower, int &higher)
{
lower = mid;
mid = (higher + lower)/2;
}
void rangeL(int &mid, int &lower, int &higher)
{
higher = mid;
mid = (higher + lower)/2;
}
void failP(int &times)
{                      
if (times == 7)
{
cout<<"What? That was supossed to be your number. Don't cheat on me!"<<endl;
}
}
void IWinn()
{                          
cout<<"Yay! I win! Now give me my 100$!"<<endl;
}
int main()
{
char a, r, b;
bool play = true;
cout<<" Welcome to the 'Guess the Number' game!"<<endl<<endl;
do
{
int min = 0;
int max = 101;
int mid = (min + max) / 2;
play = true;
cout<<endl<<"Think of a number between 1-100. I'll try to guess it in 7 or less guesses."<<endl;
cout<<"Ready? (y/n) ";
cin>>r;
if (r == 'y')
{
for (int j = 1;j<=7;j++)
{
cout<<"Guess "<<j<<":"<<endl;
cout<<"Is your number: "<<mid<<"?"<<endl;
cout<<" 'c' -> I'm correct"<<endl;
cout<<" 'l' -> Number is lower"<<endl;
cout<<" 'h' -> Number is higher"<<endl;
cin>>b;
if (b == 'c')
{
IWinn();
break;
}
else if (b == 'l')
{
rangeL(mid,min,max);
}
else if (b == 'h')
{
rangeH(mid,min,max);
}
else
{
cout<<"You entered an invalid character!"<<endl;
break;
}
failP(j);
}
}
else if (r == 'n')
{
cout<<"Come back when you're ready then"<<endl;
}
else
{
cout<<"You entered an invalid character!"<<endl;
}
cout<<endl<<"Do you want to play again? (y/n) ";
cin>>a;
if (a == 'n')
{
play = true;
}
else if (a == 'y')
{
play = false;
}
}
while (!play);
cout<<endl<<"Thanks for playing!"<<endl<<endl;
return 0;
}