Number Guessing Game using C++
Posted by Samath
Last Updated: January 04, 2017

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; 
}

 

Related Content
Casino Number Guessing Game in C++
Casino Number Guessing Game in C++
Samath | Jan 20, 2024
The Matching Game in Java
The Matching Game in Java
Samath | Mar 20, 2015
Hangman Game in C++
Hangman Game in C++
Samath | Jan 17, 2024
Hangman Game using C#
Hangman Game using C#
Samath | Jan 17, 2024
Animal Game in Java
Animal Game in Java
gideonna | Apr 13, 2016
Blackjack Game in C++
Blackjack Game in C++
Samath | Jan 05, 2017
Checkers Game using C++
Checkers Game using C++
Samath | Jan 17, 2024
Minesweeper Game using C++
Minesweeper Game using C++
Samath | Jan 05, 2017
Craps Dice game in C++
Craps Dice game in C++
Samath | Jan 06, 2021
Paper Strip Game using Python
Paper Strip Game using Python
Samath | Jan 17, 2024
Tic Tac Toe Game using C#
Tic Tac Toe Game using C#
Samath | Jan 17, 2024
John Conway's Game of Life using C++
John Conway's Game of Life using C++
Samath | Jan 04, 2017
C++ Rock Paper Scissors Game
C++ Rock Paper Scissors Game
Samath | Jan 05, 2017
Tic Tac Toe Game using Python
Tic Tac Toe Game using Python
Samath | Jan 17, 2024