In: Computer Science
Random Number Guessing Game Write a program in C++ that generates a random number between 1 and 100 and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high. Try again.” If the user’s guess is lower than the random number, the program should display “Too low. Try again.” The program should use a loop that repeats until the user correctly guesses the random number. Then the program should display “Congratulations. You figured out my number.” Also Enhance the program so it keeps a count of the number of guesses the user makes. When the user correctly guesses the random number, the program should display the number of guesses along with the message of congratulations. d. Use of sufficient comments to clarify use of syntax. e. Use of meaningful variable (identifier) in your program f. Separate input, process, and output instructions by a comment (In-Process-Out) g. Working program without any error
Hi, I have written a simple c++ program as you requested. I have added appropriate comments, I hope it will be easy to understand. Please find the code below.
#include <iostream>
using namespace std;
int main() {
// Seed the time to generate random number
srand(time(NULL));
// generate a random Number
int randomNumber = rand()%100+1;
// flag to check if user has made the correct guess, initial value will be false
bool guessCheck=false;
// initiate total number of guesses as 0
int totalGuesses=0;
// loop until the user makes a correct guess , i.e. loop till guessCheck is true
while(!guessCheck){
// temporary variable to store user input
int userGuess;
cout<<"guess a number between 1 and 100\n";
// GET USER INPUT
cin>>userGuess;
// END USER INPUT
// The totalGuesses count will now increase by one, as user made a guess
totalGuesses++;
// PROCESS
// check if user has made the correct guess, i.e. check if it is equal to randomNumber
if(userGuess==randomNumber){
// if true print the required output
// OUTPUT START
cout<<"Congratulations. You figured out my number\n";
cout<<"You have made "<<totalGuesses<<" guesses \n";
// OUTPUT END
// now that user has made the correct guess, set guessCheckas true to stop the loop
guessCheck=true;
}
// if userGuess is greater than randomNumber print too high, try again
if(userGuess>randomNumber){
// OUTPUT START
cout<<"Too high. Try again.\n";
// OUTPUT END
}
// if userGuess is less than randomNumber print too low, try again
if(userGuess<randomNumber){
// OUTPUT END
cout<<"Too low. Try again.\n";
// OUTPUT END
}
}
return 0;
}