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

Write a number guessing program. You should think of a number between 1 and 100.

ID: 3819200 • Letter: W

Question

Write a number guessing program.

You should think of a number between 1 and 100. Then, over and over again, the computer can suggest an answer. If that answer is too small, you enter the character >. If the computer's answer is too large, you enter the character <. If the computer's answer is just right, you print "You win!"

First write a program to play this game once, until the computer wins. After that is working, write a program that plays the game over and over, each time with a different number. You can use the random number generator to generate the numbers. Count the number of guesses for each game, and print the average number of guesses.

There is a slow algorithm for finding the number, and a faster algorithm. The slow algorithm is acceptable, but the fast algorithm is much better. Use the fastest algorithm you can think of. I will give hints later if you ask for them.

Explanation / Answer

#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */

using namespace std;

int getRandomInRange(int lower, int higher)
{
return rand()%(higher-lower + 1) + lower;
}

int main()
{
srand (time(NULL));

int n;
int low = 1;
int high = 100;
int guess;
int guessCount = 0;
char input;
while(true)
{
guess = getRandomInRange(low, high);
guessCount++;
cout << "My guess is: " << guess << endl;
cout << "Enter guessed number is: c correct < higher > lower ";
cin >> input;
if (input == 'c')
{
cout << "Correct guess. " << guessCount << " guesses."<< endl;
break;
}
else
{
if (input == '<')
{
high = guess;
}
else
{
low = guess;
}
}
}

return 0;
}

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