Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Seed a Random Number Generator in C++?
Next article icon

Number Guessing Game in C++ using rand() Function

Last Updated : 05 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will develop a C++ game for guessing a secret number with three difficulty levels. 

  • In this game, the computer generates a secret number in the range of 1 to 100, and the player has to guess it.
  • The game has three difficulty levels. A player's chances of guessing are limited by the level they choose. The easy level gives the player 10 chances to guess the secret number, the medium level 7 chances, whereas the difficult level only offers 5 chances.
  • During the game, a player tells the computer his assumption about a number, and the computer tells if the player is correct. If his number is less or more than the secret number, the computer informs the player, and the player tries again. 
  • The player can also end the game at any time. 

Approach 

Step 1: Generate a Random Secret Number Between 1 & 100 
No function in C++ generates a random function in a given range. Therefore, we will use the rand() function. We will need the cstdlib library to use rand(). The formula to generate a random function within a range is

randomNumber = (rand() % (upper-lower) + 1)

Let's say we wish to generate a number between 1 and 100, so upper equals 100, and lower equals 1. So, the formula becomes

randomNumber = (rand() % (100-1) + 1)

Now, every time we run the program, the computer generates the same random number as the secret number, making it quite repetitive, and boring and this one-time game loses its essence. 
To generate different random numbers each time the program runs, we will use the srand(time(0)) function. This function changes the seed each time the program runs. time(0) returns the number of seconds that the system clock shows. Since we will be using the time function, we will have to include the ctime library.

Step 2: Ask the User to Select the Level of Difficulty 
While loops let us implement a menu-driven program in which the player can select the degree of difficulty. The user can press 1 to select the easy level, 2 for medium, and 3 for the hard difficulty level. 

Step 3: Determine the Number of Chances the Player has Based on the Level of Difficulty
When the player selects the easy level, he gets 10 chances to guess the secret number. With medium, he has 7 chances while with hard, he has 5. 

Step 4: Check Whether the Entered Number is Equal to the Secret Number 
Using the if-else construct, we will check if the entered number matches the secret number. 

  • As the player is granted 10 chances at the easy level, we will iterate from 1 to 10 to determine if the entered number matches the actual secret number. Since the player has only seven choices in level medium, we iterate from 1 to 7 to check if the number matches the secret number. We will iterate from 1 to 5 if the player selects hard level since there are only 5 choices.
  • We will display that the secret number is smaller than the chosen number if the entered number is smaller than the secret number.
  • Whenever the entered number exceeds the secret number, we will display that the secret number is greater, which serves as a hint for the player.
  • We will also display the number of choices left. 
  • Once the number entered matches the secret number, the player will be notified that he has won. 
  • The game ends if the player cannot guess the number and he or she has no more choices left. This terminates the game. 

Implementation:

C++
#include <cstdlib> #include <ctime> #include <iostream> using namespace std;  int main() {      cout << "\n\t\t\tWelcome to GuessTheNumber game!"          << endl;     cout << "You have to guess a number between 1 and 100. "             "You'll have limited choices based on the "             "level you choose. Good Luck!"          << endl;      while (true) {         cout << "\nEnter the difficulty level: \n";         cout << "1 for easy!\t";         cout << "2 for medium!\t";         cout << "3 for difficult!\t";         cout << "0 for ending the game!\n" << endl;          // select the level of difficulty         int difficultyChoice;         cout << "Enter the number: ";         cin >> difficultyChoice;          // generating the secret number         srand(time(0));         int secretNumber = 1 + (rand() % 100);         int playerChoice;          // Difficulty Level:Easy         if (difficultyChoice == 1) {             cout << "\nYou have 10 choices for finding the "                     "secret number between 1 and 100.";             int choicesLeft = 10;             for (int i = 1; i <= 10; i++) {                  // prompting the player to guess the secret                 // number                 cout << "\n\nEnter the number: ";                 cin >> playerChoice;                  // determining if the playerChoice matches                 // the secret number                 if (playerChoice == secretNumber) {                     cout << "Well played! You won, "                          << playerChoice                          << " is the secret number" << endl;                     cout << "\t\t\t Thanks for playing...."                          << endl;                     cout << "Play the game again with "                             "us!!\n\n"                          << endl;                     break;                 }                 else {                     cout << "Nope, " << playerChoice                          << " is not the right number\n";                     if (playerChoice > secretNumber) {                         cout << "The secret number is "                                 "smaller than the number "                                 "you have chosen"                              << endl;                     }                     else {                         cout << "The secret number is "                                 "greater than the number "                                 "you have chosen"                              << endl;                     }                     choicesLeft--;                     cout << choicesLeft << " choices left. "                          << endl;                     if (choicesLeft == 0) {                         cout << "You couldn't find the "                                 "secret number, it was "                              << secretNumber                              << ", You lose!!\n\n";                         cout << "Play the game again to "                                 "win!!!\n\n";                     }                 }             }         }          // Difficulty level : Medium         else if (difficultyChoice == 2) {             cout << "\nYou have 7 choices for finding the "                     "secret number between 1 and 100.";             int choicesLeft = 7;             for (int i = 1; i <= 7; i++) {                  // prompting the player to guess the secret                 // number                 cout << "\n\nEnter the number: ";                 cin >> playerChoice;                  // determining if the playerChoice matches                 // the secret number                 if (playerChoice == secretNumber) {                     cout << "Well played! You won, "                          << playerChoice                          << " is the secret number" << endl;                     cout << "\t\t\t Thanks for playing...."                          << endl;                     cout << "Play the game again with "                             "us!!\n\n"                          << endl;                     break;                 }                 else {                     cout << "Nope, " << playerChoice                          << " is not the right number\n";                     if (playerChoice > secretNumber) {                         cout << "The secret number is "                                 "smaller than the number "                                 "you have chosen"                              << endl;                     }                     else {                         cout << "The secret number is "                                 "greater than the number "                                 "you have chosen"                              << endl;                     }                     choicesLeft--;                     cout << choicesLeft << " choices left. "                          << endl;                     if (choicesLeft == 0) {                         cout << "You couldn't find the "                                 "secret number, it was "                              << secretNumber                              << ", You lose!!\n\n";                         cout << "Play the game again to "                                 "win!!!\n\n";                     }                 }             }         }         // Difficulty level : Medium         else if (difficultyChoice == 3) {             cout << "\nYou have 5 choices for finding the "                     "secret number between 1 and 100.";             int choicesLeft = 5;             for (int i = 1; i <= 5; i++) {                  // prompting the player to guess the secret                 // number                 cout << "\n\nEnter the number: ";                 cin >> playerChoice;                  // determining if the playerChoice matches                 // the secret number                 if (playerChoice == secretNumber) {                     cout << "Well played! You won, "                          << playerChoice                          << " is the secret number" << endl;                     cout << "\t\t\t Thanks for playing...."                          << endl;                     cout << "Play the game again with "                             "us!!\n\n"                          << endl;                     break;                 }                 else {                     cout << "Nope, " << playerChoice                          << " is not the right number\n";                     if (playerChoice > secretNumber) {                         cout << "The secret number is "                                 "smaller than the number "                                 "you have chosen"                              << endl;                     }                     else {                         cout << "The secret number is "                                 "greater than the number "                                 "you have chosen"                              << endl;                     }                     choicesLeft--;                     cout << choicesLeft << " choices left. "                          << endl;                     if (choicesLeft == 0) {                         cout << "You couldn't find the "                                 "secret number, it was "                              << secretNumber                              << ", You lose!!\n\n";                         cout << "Play the game again to "                                 "win!!!\n\n";                     }                 }             }         }         // To end the game         else if (difficultyChoice == 0) {             exit(0);         }         else {             cout << "Wrong choice, Enter valid choice to "                     "play the game! (0,1,2,3)"                  << endl;         }     }     return 0; } 


Output: Let's try the game with Medium difficulty, and we'll see how it goes. 

Output: Guess the secret Number
Output 

Time complexity: O(1)
Auxiliary Space: O(1)


Next Article
How to Seed a Random Number Generator in C++?
author
codesaurav
Improve
Article Tags :
  • C++ Programs
  • C++
Practice Tags :
  • CPP

Similar Reads

  • How to Generate Random Number in Range in C++?
    In C++, we have a <random> header that consists of standard library facilities for random number generation. In this article, we will learn how to generate a random number in range in C++. Example: Input: Range: 1 to 20Output: Random number between 1 and 20 is: 18Generating a Random Number in
    2 min read
  • Generate Random Double Numbers in C++
    Double is a data type just like a float but double has 2x more precision than float. One bit for the sign, 11 bits for the exponent and 52* bits for the value constitute the 64-bit IEEE 754 double precision Floating Point Number known as "double." Double has 15 decimal digits of precision. In this a
    2 min read
  • Generate a random Binary String of length N
    Given a positive integer N, the task is to generate a random binary string of length N. Examples: Input: N = 7Output: 1000001 Input: N = 5Output: 01001 Approach: The given problem can be solved by using the rand() function that generates a random number over the range [0, RAND_MAX] and with the help
    5 min read
  • How to Create a Random Alpha-Numeric String in C++?
    Creating a random alpha-numeric string in C++ means generating random characters from the set of alphanumeric characters (i.e., ‘A’-‘Z’, ‘a’-‘z’, and ‘0’-‘9’) and appending them to a string. In this article, we will learn how to create a random alpha-numeric string in C++. Example Output:a8shg1laCre
    2 min read
  • How to Seed a Random Number Generator in C++?
    In C++, seeding a random number generator is important for generating different sequences of random numbers on each program run. This process consists of initializing the generator with a starting value, known as a seed. This ensures the randomness and unpredictability required for various applicati
    2 min read
  • Slider and Ball Game using Computer Graphics in C++
    Computer graphics provide an exciting platform for developing fun and interactive games. In this article, we will walk you through the creation of a simple yet entertaining slider and ball game using the C++ programming language and the graphics.h library. Prerequisites: C++ Graphics and Development
    8 min read
  • C++ program to generate random number
    The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function. Prerequisite : random header in C++ | Set 1(Generators) // C++ program to generate random number #include <bits/stdc++.h> using namespace std; // Funct
    1 min read
  • std::uniform_real_ distribution class in C++ with Examples
    In Probability, Uniform Distribution Function refers to the distribution in which the probabilities are defined on a continuous random variable, one which can take any value between two numbers, then the distribution is said to be a continuous probability distribution. For example, the temperature t
    3 min read
  • std::uniform_int_distribution class in C++
    In Probability, Discrete Uniform Distribution Function refers to the distribution with constant probability for discrete values over a range and zero probability outside the range. The probability density function P(x) for uniform discrete distribution in interval [a, b] is constant for discrete val
    3 min read
  • Dice simulator with sound using graphics
    Graphics are defined as any sketch or a drawing or a special network that pictorially represents some meaningful information. Computer Graphics is used where a set of images needs to be manipulated or the creation of the image in the form of pixels and is drawn on the computer. It can be used in dig
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences