Metadata


Notes

Detailed Notes on Creating a Simple Number Guessing Game in C++

In this tutorial, we will create a simple number guessing game using basic concepts like random number generation, loops, conditionals, and user input. This game will randomly generate a number between 1 and 100, and the user will try to guess that number. We’ll provide feedback on whether the guess is too high or too low, and the game will continue until the user guesses correctly. The game will also track how many attempts (or “tries”) it takes for the user to find the correct number.


1. Setting Up the Game: Declaring Variables

First, we need to declare the necessary variables:

  • num: This will store the random number that the user needs to guess.
  • guess: This will hold the player’s current guess.
  • tries: This will track the number of guesses the player makes until they guess the correct number.
int num;      // The number to be guessed
int guess;    // The player's guess
int tries = 0; // Counter for the number of attempts
 

2. Generating a Random Number

We will generate a random number between 1 and 100. To do this, we use the rand() function and the srand() function to seed the random number generator.

Steps:

  1. Seed the RNG: We need to initialize the random number generator with a seed value. The time(0) function provides the current time, which helps in ensuring different random numbers are generated each time the program runs.

    srand(time(0)); // Seed the RNG with the current time
     
  2. Generate a Random Number: The rand() function generates a pseudo-random number, and using the modulus operator (%), we can limit it to a specific range. To get a number between 1 and 100, we use the following formula:

    num = rand() % 100 + 1; // Generate a number between 1 and 100
     
  • Explanation:
    • rand() % 100: This will generate a number between 0 and 99.
    • + 1: We add 1 to shift the range to 1–100.

3. Game Loop with a Do-While Loop

To allow the player to keep guessing until they find the correct number, we use a do-while loop. A do-while loop ensures that the code inside the loop runs at least once, even if the condition isn’t met initially.

Structure of the do-while loop:

do {
    // Code to prompt user and check guess
} while (guess != num); // Continue looping until the guess equals the random number
 

Inside the loop:

  • The player is prompted to enter a guess between 1 and 100.
  • After each guess, we check whether the guess is too high, too low, or correct.
// User Input Prompt
std::cout << "Enter a guess between 1 and 100: ";
std::cin >> guess;  // Get player's guess
tries++; // Increment the tries counter
 

4. Checking the Guess

After getting the player’s guess, we need to compare it with the randomly generated number and give feedback. If the guess is:

  • Greater than the random number: We display “Too high”.
  • Less than the random number: We display “Too low”.
  • Equal to the random number: We display “Correct!” and end the loop.

Code Implementation:

if (guess > num) {
    std::cout << "Too high!" << std::endl;
} else if (guess < num) {
    std::cout << "Too low!" << std::endl;
} else {
    std::cout << "Correct!" << std::endl;
    std::cout << "It took you " << tries << " tries." << std::endl;
}
 

5. Displaying Results

Once the player guesses the correct number, the loop will exit, and the program will display how many tries it took to guess the correct number. For some extra decoration, we can add a message after the correct guess, like “Thanks for playing!”

Example Output:

Enter a guess between 1 and 100: 50
Too low!

Enter a guess between 1 and 100: 75
Too high!

Enter a guess between 1 and 100: 62
Too high!

Enter a guess between 1 and 100: 56
Too high!

Enter a guess between 1 and 100: 53
Too low!

Enter a guess between 1 and 100: 54
Too low!

Enter a guess between 1 and 100: 55
Correct!
It took you 7 tries.
Thanks for playing!

6. Final Game Code

Here’s the complete code for the Number Guessing Game:

#include <iostream>
#include <cstdlib>
#include <ctime>
 
int main() {
    // Seed the random number generator
    srand(time(0));
 
    int num;        // The number to be guessed
    int guess;      // Player's guess
    int tries = 0;  // Number of tries
 
    // Generate a random number between 1 and 100
    num = rand() % 100 + 1;
 
    // Game title
    std::cout << "Welcome to the Number Guessing Game!" << std::endl;
 
    // Start the do-while loop for guessing
    do {
        std::cout << "Enter a guess between 1 and 100: ";
        std::cin >> guess;
        tries++;  // Increment the tries count
 
        if (guess > num) {
            std::cout << "Too high!" << std::endl;
        } else if (guess < num) {
            std::cout << "Too low!" << std::endl;
        } else {
            std::cout << "Correct!" << std::endl;
            std::cout << "It took you " << tries << " tries." << std::endl;
        }
    } while (guess != num);
 
    std::cout << "Thanks for playing!" << std::endl;
 
    return 0;
}
 

Conclusion

The Number Guessing Game is a great example of how to:

  • Generate random numbers using the rand() and srand() functions.
  • Use loops (specifically do-while loops) to repeatedly prompt the player for guesses until they succeed.
  • Use conditionals (if, else if, and else) to provide feedback to the player on whether their guess is too high, too low, or correct.

This simple game can be expanded in various ways, such as adding a scoring system, allowing the player to play multiple rounds, or implementing difficulty levels. It’s a great starting point for beginners to practice C++ programming concepts.


References