Print Friendly and PDF
(Guess-the-Number Game) Write a program that plays the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays the following:
(Guess-the-Number Game) Write a program that plays the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays the following:

I have a number between 1 and 1000.

Can you guess my number?

Please type your first guess.

The player then types a first guess. The program responds with one of the following:

1. Excellent! You guessed the number!

Would you like to play again (y or n)?

2. Too low. Try again.

3. Too high. Try again.

Solution:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cstdlib>
#include <ctime>
 
int main()
{
   srand(time(0));
   int guess;
   int number;
   char selection = 'y';
 
   while(selection == 'y')
   {
      number = rand() % 1000 + 1;
 
      cout << "(Hint: Number is " << number << ")." << endl; //check the program for cheating
 
      cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess.";
      cin >>guess;
 
      while(number != guess)
      {
         if(number > guess)
         {
            cout << "Too low. Try again." << endl;
            cin >> guess;
         }
         if(number < guess)
         {
            cout << "Too high. Try again." << endl;
            cin >> guess;
         }
 
      }
      cout << "Excellent! You guessed the number!\nWould you like to play again (y or n)?";
      cin >> selection;
   }
   cout << "Thank you!";
   return 0;
}
 
 
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: