Guess the Number Game (1-100) in C++
In this exercise, you will implement a program that simulates a simple number guessing game. The program will generate a random number between 1 and 100, and the player will attempt to guess it. After each guess, the program provides feedback: too high, too low, or correct.
The game uses random number generation and a do-while loop to ensure the player can keep trying until they find the target number.
How it works
Random Seeding
We use srand(time(0)) to seed the generator, ensuring a different "random" sequence every time the game starts.
Feedback Loop
A do-while loop processes the logic, checking the condition after the user makes their first attempt.
Pro Tip: Why time(0)?
If you don't use srand(time(0)), the rand() function will generate the exact same number every time you run the program! Computers are deterministic; using the current time as a "seed" makes the randomness feel real to the user.
Objective
- 1. Generate a random number between 1 and 100 using
rand() % 100 + 1. - 2. Ask the user for input and store it in a variable.
- 3. Compare the guess using if/else if structures.
- 4. Track the number of attempts with an incrementing counter.
- 5. End the loop only when the guess matches the target number.
Example C++ Code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // Seed the generator
int targetNumber = rand() % 100 + 1;
int guess;
int attempts = 0;
cout << "Welcome to the Guess the Number Game!\n";
do {
cout << "Enter your guess: ";
cin >> guess;
attempts++;
if (guess < targetNumber) {
cout << "Your guess is too low.\n";
} else if (guess > targetNumber) {
cout << "Your guess is too high.\n";
} else {
cout << "Correct! Attempts: " << attempts << endl;
}
} while (guess != targetNumber);
return 0;
}
Console Output:
Enter your guess: 50
Your guess is too high. Try again.
Enter your guess: 25
Congratulations! You've guessed the number in 2 attempts.