Time to combine loops with conditionals! Create an interactive game where the computer picks a random number and the player tries to guess it.
YOUR TASK
Create a program that:
Generates a random number between 1 and 100
Asks the player to guess the number
Gives hints: "Too high!" or "Too low!"
Counts the number of attempts
Congratulates when correct and shows attempt count
Game Flow:
Computer generates a secret number (1-100)
Player enters a guess
If guess is too high: display "Too high! Try again."
If guess is too low: display "Too low! Try again."
If correct: display success message with attempt count
Keep looping until the player guesses correctly
Hint 1: Random Number Generation
To generate random numbers:
1. Include: #include <cstdlib> and #include <ctime>
2. Seed the random generator: srand(time(0));
3. Generate number: int secret = rand() % 100 + 1;
This gives a number between 1 and 100
Hint 2: Loop Structure
Use a while loop:
• Declare int guess; and int attempts = 0;
• Use while (guess != secret)
• Inside loop: ask for input, increment attempts
• Compare guess with secret number
• Give appropriate hint or break if correct
Hint 3: Comparison Logic
Inside your loop:
1. Get player's guess
2. Increment attempts counter
3. if (guess > secret) → "Too high!"
4. else if (guess < secret) → "Too low!"
5. else → Correct! Display attempts and exit loop
Hint 4: Full Solution Outline
Complete structure:
1. Set up random number generation (srand, rand)
2. Generate secret number
3. Initialize guess = 0 and attempts = 0
4. Display welcome message
5. While loop (guess != secret):
• Ask for guess
• Increment attempts
• Compare and give hint
6. After loop: display success message
Example Game Flow
Secret: 42, Guess 50 → "Too high! Try again."
Secret: 42, Guess 30 → "Too low! Try again."
Secret: 42, Guess 42 → "Correct! You won in X attempts!"
Example Run (secret = 42):
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 50
Too high! Try again.
Enter your guess: 30
Too low! Try again.
Enter your guess: 42
Congratulations! You guessed it in 3 attempts!
Code Editor
Ready
Output
Console
Console initialized...
Ready for Practice Project 4: Number Guessing Game
> Build an interactive guessing game with loops!
> Use the "Check My Code" button to validate
> Test with different secret numbers to ensure it works!