C++ Write a program that generates a random number between 1 and 100 and asks th
ID: 664150 • Letter: C
Question
C++
Write a program that generates a random number between 1 and 100 and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program must use a loop that repeats until the user correctly guesses the random number or has made 10 guesses. The program needs to keep track of the number of guesses the user makes. At the end the program will display one of the messages in the table below based on the number of guesses the user took. The program must validate the user’s guess by making sure the value entered is between 1 and 100. If the value is not between 1 and 100, the user should be told to make another guess. The invalid input should not count as one of the 10 guesses the user is allowed.
Number of Guesses by the User
Output Message
Less than 5 guesses
"Either you know the secret or you got lucky!"
5-7 guesses
"You're pretty good at this!"
8-10 guesses
"You'll do better next time."
If guess 10 is not correct
"Sorry - You have taken too many guesses."
Number of Guesses by the User
Output Message
Less than 5 guesses
"Either you know the secret or you got lucky!"
5-7 guesses
"You're pretty good at this!"
8-10 guesses
"You'll do better next time."
If guess 10 is not correct
"Sorry - You have taken too many guesses."
Explanation / Answer
#include <iostream.h>
#include<stdlib.h>
int main ()
{
int secret, guess,count=0; /* count variable is taken to keep track of no of guesses*/
/* generate secret number between 1 and 100: */
seecret = rand() % 100 + 1;
do
{
label:
cout <<"Please Guess The Secret No" << endl;
cin >> guess;
if(guess<1 || guess>100) /*Validates the input is between 1 & 100 or not */
goto label;
count++;
if(guess>secret) /* Checks if guess is greater than secret */
cout << "TO high,try again." <<endl ;
else if(guess<secret) /* Checks if guess is lower than secret */
cout <<"TO low,try again." <<endl ;
else /* Displays the corresponding message depanding on count ,if the guess is correct */
{
if(count<5)
cout <<"Either you know the secret or you got lucky!" << endl;
else if(count>=5 && count <8)
cout <<"you're pretty good at this!" <<endl;
else if(count>=8 && count <=10)
cout <<"you'll do better next time." <<endl;
else
cout <<"Sorry -you have taken too many guesses" << endl;
}
} while (secret!=guess && count<=10);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.