Introduction
The “Number Guessing Game” is a fun and interactive game where the computer randomly selects a number, and the user is tasked with guessing it. This game allows users to improve their problem-solving skills and learn how to work with random numbers and user input in C++ programming.
Objective
The goal of the game is simple: the computer will randomly select a number between a specified range (e.g., 1 to 100). The player will have to guess the number, and the game will provide feedback on whether the guess is too high, too low, or correct. The user will continue guessing until they find the correct number.
Program Code
#include #include #include using namespace std; int main() { // Seed the random number generator srand(static_cast(time(0))); // Define the range for the random number int lower = 1, upper = 100; // Generate a random number between lower and upper int targetNumber = rand() % (upper - lower + 1) + lower; int guess; int numberOfGuesses = 0; cout << "Welcome to the Number Guessing Game!" << endl; cout << "I have selected a number between " << lower << " and " << upper << ". Try to guess it!" << endl; // Start the guessing loop do { cout << "Enter your guess: "; cin >> guess; numberOfGuesses++; if (guess < targetNumber) { cout << "Too low! Try again." << endl; } else if (guess > targetNumber) { cout << "Too high! Try again." << endl; } else { cout << "Congratulations! You guessed the number " << targetNumber << " in " << numberOfGuesses << " attempts!" << endl; } } while (guess != targetNumber); return 0; }
Program Explanation
The program works as follows:
- The program first seeds the random number generator using
srand()
andtime(0)
to ensure different results each time the program is run. - A random number between 1 and 100 is generated using the
rand()
function. This number is the target the user needs to guess. - The program then enters a loop where the user is prompted to enter a guess. The loop continues until the user guesses the correct number.
- After each guess, the program gives feedback. It tells the user if the guess is too low, too high, or correct.
- Once the user guesses the correct number, the program congratulates them and displays how many attempts it took to guess the number.
How to Run the Program
To run this program, follow these steps:
- Install a C++ compiler, such as GCC or an IDE like Code::Blocks, Visual Studio, or Xcode.
- Open the IDE or a text editor and copy the provided code into a new file. Save the file with a
.cpp
extension, for example,guess_game.cpp
. - Compile the code using the C++ compiler. If you are using a terminal or command prompt, use the command
g++ guess_game.cpp -o guess_game
. - Run the compiled program by typing
./guess_game
(on Linux/macOS) orguess_game.exe
(on Windows). - Enjoy playing the game!