Write a C++ program to implement the Number Guessing Game. In this game the computer chooses a random number, and the player tries to guess the number in as few attempts as possible. Each time the player enters a guess, the computer tells him whether the guess is too high, too low, or right. Once the player guesses the number, the game is over.
This is C++ sample code for game that lets user guess the number generated by program. We are using
this game to demontrate the use of 'if', 'else if', and 'else' statements.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int number = rand() % 100 + 1;
bool is_guess_correct = false;
int input_number;
int attempts_count = 1;
while(is_guess_correct == false)
{
if(attempts_count == 1)
{
cout << "Enter Number: ";
}
else
{
cout << "Enter Number Again: ";
}
cin >> input_number;
if(input_number == number)
{
cout << "Congratulation! You have guessed the correct number in " << attempts_count << " attempts" << endl;
is_guess_correct = true;
}
else
{
attempts_count++;
if(input_number < number)
{
cout << "The number you entered is too small." << endl;
}
else
{
cout << "the numner you entered is too large." << endl;
}
}
}
return 0;
}