In: Computer Science
Random Number Guessing Game
C++. Write a program that generates a random number between 5 and
20 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 should use a
loop that repeats while keeping a count of the number of guesses
the user makes until the user correctly guesses the random number.
Then the program should display the number of guesses along with
the following message Congratulations. You figured out
my number.
The algorithm should provide the user the opportunity to play the game again or quit.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char ch='y';
int n=0,num,temp=0;
srand(time(0));
while(ch=='y') //Checking for user's choice
{
num = rand() % (20-5+1)+5; //Generating random number
temp = 0;
while(n!=num)
{
cout<<"\nEnter your guess: ";
cin>>n; //Taking input from user
if(n<num) //Checking if user entered small value
cout<<"\nToo low,Try again";
if(n>num) //Checking if user entered big value
cout<<"\nToo high,Try again";
temp++;
}
cout<<"\nCongratulations you figured out the number in
"<<temp<<" attempts"; //Printing ans
cout<<"\nDo you want to play again? ";
cin>>ch; //Taking user's choice
}
return 0;
}
Output:-