Answer:
The c++ program for the number guessing game is given below.
#include <iostream>
using namespace std;
// method declaration without parameters
void game();
int main() {
char reply;
// calling the game method
game();
cout<<"Would you like to play again (y or n)? " <<endl;
cin>>reply;
if(reply == 'y')
game();
if(reply == 'n')
cout<<"Quitting the game..."<<endl;
return 0;
}
void game()
{
int num, guess;
num = (rand() % 10) + 60;
cout<<endl<<"Welcome to the game of guessing the correct number "<<endl;
do
{
do
{
cout<<"Guess any number between 1 and 1000. "<< endl;
cin>>guess;
if(guess<1 || guess>1000)
{
cout<<"Invalid number. Guess any number between 1 and 1000. "<<endl;
cin>>guess;
}
}while(guess<1 || guess>1000);
if(guess < num)
{
cout<<"Too Low. Try again."<<endl;
}
if(guess > num)
{
cout<<"Too High. Try again."<<endl;
}
}while(guess != num);
cout<<"Excellent! You guessed the number!"<<endl;
}
OUTPUT
Welcome to the game of guessing the correct number
Guess any number between 1 and 1000.
45
Too Low. Try again.
Guess any number between 1 and 1000.
56
Too Low. Try again.
Guess any number between 1 and 1000.
63
Too High. Try again.
Guess any number between 1 and 1000.
61
Too High. Try again.
Guess any number between 1 and 1000.
57
Too Low. Try again.
Guess any number between 1 and 1000.
58
Too Low. Try again.
Guess any number between 1 and 1000.
59
Too Low. Try again.
Guess any number between 1 and 1000.
60
Excellent! You guessed the number!
Would you like to play again (y or n)?
n
Quitting the game...
Explanation:
The expression
(rand() % 10)
generates a random number between 0 and 9. 6 is added to generate a random number between 5 and 15.
The integer variable attempt is initialized to 0.
Next, user is asked to guess the number. If the user enters an invalid input, the do-while loop executes until a valid input is received from the user.
do
{
cout<<"Enter any number between 5 and 15. "<< endl;
cin>>guess;
if(guess<5 || guess>15)
{
cout<<"Invalid number. Enter any number between 5 and 15. "<<endl;
cin>>guess;
}
attempt++;
}while(guess<5 || guess>15);
User is prompted to input the guess using the same do-while loop as above. Until the user guesses the correct number, the loop continues. Each incorrect guess by the user, increments the variable attempt by 1. This represents the number of attempts done by the user to guess the correct number.
if(guess < num)
{
cout<<"Too Low"<<endl;
}
if(guess > num)
{
cout<<"Too High"<<endl;
}
The random number generation and the guessing logic is put in a separate method game().
The entry and exit from the game only is put inside the main method.