pum game in c++
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(static_cast<unsigned int>(time(0))); // Seed for random number generator
int randomNumber = (rand() % 100) + 1; // Generate random number between 1 and 100
int guess;
int attempts = 0;
std::cout << "Welcome to the Number Guessing Game!\n";
std::cout << "Try to guess the number between 1 and 100.\n";
do {
std::cout << "Enter your guess: ";
std::cin >> guess;
attempts++;
if (guess > randomNumber) {
std::cout << "Too high! Try again.\n";
} else if (guess < randomNumber) {
std::cout << "Too low! Try again.\n";
} else {
std::cout << "Congratulations! You guessed the number in " << attempts << " attempts!\n";
}
} while (guess != randomNumber);
return 0;
}
Explanation:
#include <iostream>
: Includes the input-output stream header file for handling input and output operations.#include <cstdlib>
: Includes the C Standard General Utilities Library for functions such asrand()
andsrand()
.#include <ctime>
: Includes the C Time library to work with time-related functions.srand(static_cast<unsigned int>(time(0)));
: Seeds the random number generator with the current time to ensure different random numbers are generated in each program execution.int randomNumber = (rand() % 100) + 1;
: Generates a random number between 1 and 100 using therand()
function and%
operator to limit the range.int guess;
: Declares a variable to store the user's guessed number.int attempts = 0;
: Initializes a variable to count the number of attempts made by the user.std::cout << "Welcome to the Number Guessing Game!\n";
: Outputs a welcome message to the user.std::cout << "Try to guess the number between 1 and 100.\n";
: Instructs the user on how to play the game.do { ... } while (guess != randomNumber);
: Executes a loop that continues until the user's guessed number matches the randomly generated number.std::cout << "Enter your guess: ";
: Prompts the user to input their guess.std::cin >> guess;
: Takes user input and stores it in theguess
variable.attempts++;
: Increments the attempts counter after each guess.if (guess > randomNumber) { ... } else if (guess < randomNumber) { ... } else { ... }
: Checks if the guessed number is higher, lower, or equal to the random number and provides appropriate feedback to the user accordingly.return 0;
: Indicates successful program execution and termination.