C++ Code for a Simple Guessing Game
This article will guide you through creating a basic guessing game in C++. This game will involve the user trying to guess a randomly generated number within a specified range.
Setting up the Game
First, let's outline the core elements of our game:
- Random Number Generation: We'll use the
rand()
function to generate a random number within a specified range. - User Input: The user will enter their guess.
- Comparison: We'll compare the user's guess with the random number.
- Feedback: The program will provide feedback to the user, telling them if their guess is too high, too low, or correct.
The Code
Here's the C++ code for the guessing game:
#include
#include
#include
using namespace std;
int main() {
// Seed the random number generator
srand(time(0));
// Generate a random number between 1 and 100
int secretNumber = rand() % 100 + 1;
int guess;
int attempts = 0;
cout << "Welcome to the Guessing Game!\n";
cout << "I've chosen a secret number between 1 and 100.\n";
do {
cout << "Enter your guess: ";
cin >> guess;
attempts++;
if (guess < secretNumber) {
cout << "Too low! Try again.\n";
} else if (guess > secretNumber) {
cout << "Too high! Try again.\n";
} else {
cout << "Congratulations! You guessed it in " << attempts << " attempts!\n";
}
} while (guess != secretNumber);
return 0;
}
Explanation
-
Headers:
iostream
: Provides input/output functionalities.cstdlib
: Provides therand()
function for random number generation.ctime
: Provides thetime()
function to seed the random number generator.
-
srand(time(0))
: This line seeds the random number generator with the current time. This ensures that the generated random number changes each time you run the program. -
int secretNumber = rand() % 100 + 1;
: This line generates a random number between 1 and 100. The%
operator (modulo) gives the remainder after dividing by 100, generating a number between 0 and 99. We add 1 to include 100 in the possible range. -
int guess; int attempts = 0;
: Declares variables for the user's guess and the number of attempts. -
Input and Feedback:
- The
do...while
loop continues until the user guesses the correct number. - Inside the loop, the program prompts the user for their guess and provides feedback based on the comparison between the guess and the secret number.
- The
attempts
variable keeps track of the number of tries.
- The
-
Output: The program congratulates the user when they guess correctly and displays the number of attempts.
Running the Game
Compile and run the code. You'll be prompted to enter your guesses. Keep guessing until you get the right number!
This basic guessing game is a good starting point for learning C++ programming. You can expand upon it by adding features like:
- Difficulty levels: Allow the user to choose a range for the random number.
- Limited attempts: Limit the number of guesses allowed.
- Hints: Provide clues based on the user's guesses.
Have fun exploring and modifying this game!