simple game in C++ called Guess the Number
This program generates a random number between 1 and 100 (inclusive) and the player has to guess the number. The program will output "Too high" or "Too low" depending on the player's guess and will keep running until the player correctly guesses the number. At the end, the program will output the number of tries it took the player to guess the number.
description
The program starts by including the necessary libraries: iostream for input and output, cstdlib for the random number generator, and ctime for the time seed. The using namespace std;
line allows us to use standard library functions without having to prefix them with std::.
The main()
function is where the program starts executing. In this function, the random number generator is initialized with the current time using srand(time(0))
. This ensures that the generated random number will be different every time the program is run. The rand() % 100 + 1
generates a random number between 1 and 100 (inclusive).
The int guess
variable is used to store the player's current guess, and the int numGuesses
variable is used to keep track of how many guesses the player has made. The program then outputs a welcome message and prompts the player to guess a number.
The game loop is implemented using a do-while
loop. The loop continues until the player correctly guesses the number. Inside the loop, the player's guess is read from the input using cin >> guess
and the number of guesses is incremented by 1.
If the player's guess is too low, the program will output "Too low, try again: " and prompt the player to guess again. If the player's guess is too high, the program will output "Too high, try again: " and prompt the player to guess again. If the player's guess is correct, the program will break out of the loop.
After the loop, the program will output a congratulations message along with the number of tries it took the player to guess the number. Finally, the program returns 0 to indicate that it has finished executing without any errors.
code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int secretNum = rand() % 100 + 1;
int guess;
int numGuesses = 0;
cout << "Welcome to Guess the Number!" << endl;
cout `oaicite:{"index":0,"invalid_reason":"Malformed citation << \"Guess a number between 1 and 100: \";\n\n do\n {\n cin >>"}` guess;
numGuesses++;
if (guess < secretNum)
{
cout << "Too low, try again: ";
}
else if (guess > secretNum)
{
cout << "Too high, try again: ";
}
} while (guess != secretNum);
cout << "Congratulations! You guessed the number in " << numGuesses << " tries." << endl;
return 0;
}