PROGRAM SHOULD BE IN C++ A Better Random Number Guessing Game Keep a running cou
ID: 3909508 • Letter: P
Question
PROGRAM SHOULD BE IN C++
A Better Random Number Guessing Game
Keep a running 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 it took to guess the number.
The user should be able to play the game as many times as they wish without having to restart the program (e.g. you will need to use a loop that tests a Boolean variable such as keepPlaying – if the user wants to keep playing, then keepPlaying = true, otherwise keepPlaying = false).
Remember:
For each problem, include several test runs of the program to show successful runs of your program, with both valid and invalid data (to show that you are checking for invalid data)
Please ensure the program is well designed and follows accepted style guidelines (e.g. variable naming, indentation, spacing).
Please ensure the program is well documented, including the overall purpose of the program and documenting all the major sections of the code.
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int n;
srand (time(NULL));
bool keepPlaying = true;
int guessCount = 0;
char ch = 'y';
while(keepPlaying) {
guessCount = 0;
int random = rand() % 100 + 1;
cout << "Enter your guess between 1 and 100:" << endl;
cin >> n;
guessCount++;
while(n!=random) {
guessCount++;
if(n<random) {
cout<<"Your guess is low"<<endl;
} else {
cout<<"Your guess is high"<<endl;
}
cout << "Enter your guess between 1 and 100:" << endl;
cin >> n;
}
cout<<"Congrats. You guessed it"<<endl;
cout<<"Number of guesses: "<<guessCount<<endl;
cout<<"Do you want to continue? (y/n):"<<endl;
cin >> ch;
if(ch!='y'&&ch!='Y') {
keepPlaying = false;
}
}
return 0;
}
Output::
Number of guesses: 8
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.