Group
Advanced Conditional Structures in C++
Objective
1. Generate a random number between 1 and 100.
2. Ask the user to guess the number.
3. Compare the user's guess with the generated number.
4. Provide feedback if the guess is too high, too low, or correct.
5. Keep asking for guesses until the user guesses the correct number.
6. Display the number of attempts it took the user to guess correctly.
Implement a program that simulates the number guessing game (range 1-100).
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input/output stream
#include <cstdlib> // For random number generation
#include <ctime> // For seeding the random number generator
using namespace std;
int main() {
srand(time(0)); // Seed the random number generator with the current time
int targetNumber = rand() % 100 + 1; // Generate a random number between 1 and 100
int guess; // Variable to store the player's guess
int attempts = 0; // Counter for the number of attempts
// Introduce the game to the user
cout << "Welcome to the Guess the Number Game! The number is between 1 and 100.\n";
// Start the game loop
do {
cout << "Enter your guess: "; // Prompt the user to enter a guess
cin >> guess; // Store the user's guess
attempts++; // Increment the attempt counter
if (guess < targetNumber) {
cout << "Your guess is too low. Try again.\n"; // If guess is too low, provide feedback
} else if (guess > targetNumber) {
cout << "Your guess is too high. Try again.\n"; // If guess is too high, provide feedback
} else {
cout << "Congratulations! You've guessed the number in " << attempts << " attempts.\n"; // If guess is correct, congratulate the user
}
} while (guess != targetNumber); // Continue the loop until the correct guess is made
return 0; // Return 0 to indicate successful completion of the program
}
Output
Welcome to the Guess the Number Game! The number is between 1 and 100.
Enter your guess: 50
Your guess is too high. Try again.
Enter your guess: 25
Your guess is too low. Try again.
Enter your guess: 37
Your guess is too low. Try again.
Enter your guess: 43
Your guess is too low. Try again.
Enter your guess: 47
Your guess is too high. Try again.
Enter your guess: 45
Congratulations! You've guessed the number in 6 attempts.