Write a C++ program that will set a variable to a number between 1 to 20, for ex
ID: 3669330 • Letter: W
Question
Write a C++ program that will set a variable to a number between 1 to 20, for example 7 or whatever you wish. Then display the following on the monitor: You have 5 chances to guess my secret number that is a number between 1 to 20 Allow the user to guess the secrete number only 5 times. After each wrong guess display the following on the monitor: Sorry you are wrong this was your … attempt, you have … more chances to guess the number If the user was able to guess your secret number during the 5 attempt congratulate them, otherwise the program should stop and display: Sorry You could not guess my secrete number The number is !" Display the number for the user on the monitor..
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
//#include <Windows.h>
using namespace std;
int main() {
int number,
guess;
char playAgain;
unsigned seed = time(0);
srand(seed);
do {
// generate random number between 1 - 100
number = (rand() % (100)) + 1;
cout << "Guess the number (1-100): ";
for (int i = 0; i < 10; i++) {
cin >> guess;
// validate users input
if ((guess < 1) || (guess > 100)){
cout << endl << "You must guess a number between 1 - 100. Guess again: ";
i--;
}
// if user has 1-4 guesses
if ((guess == number) && (i < 4)) {
cout << endl << "Either you know the secret or you got lucky!" << endl;
break;
}
// if user has 5-7 guesses
else if ((guess == number) && (i > 3) && (i < 7)) {
cout << endl << "You're pretty good at this!" << endl;
break;
}
// if user has 7-10 guesses
else if ((guess == number) && (i > 6) && (i < 10)) {
cout << endl << "You'll do better next time." << endl;
break;
}
// if user has guesses 10 times and still has not guessed the number
else if ((guess != number) && (i == 9)) {
cout << endl << "Sorry You could not guess my secrete number The number is." << endl;
break;
}
else if ((guess < number) && (guess >= 1) && (guess <= 100)) {
cout << endl << "Too low, try again: ";
}
else if ((guess > number) && (guess >= 1) && (guess <= 100)) {
cout << endl << "Too high, try again: ";
}
}
cout << "Would you like to play again? (Y/N): ";
cin >> playAgain;
cout << endl;
} while ((playAgain == 'Y') || (playAgain == 'y'));
// if user doesn't hit Y or y, end and close the program
cout << "Good Bye!";
//Sleep(2000);
return 0;
}
Sample output
Guess the number (1-100): 9
Too high, try again: 4
Too low, try again: 5
Too low, try again: 5
Too low, try again: 7
low, try again: 8
You're pretty good at this!
Would you like to play again? (Y/N):
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.