In: Computer Science
Write a program in C++ coding that generates a random number between 1 and 500 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.
Count the number of guesses that the user makes. When the user correctly guesses the random number, the program should display a user-friendly message and the number of guesses.
(HINT: Design your code with an If/Else structure nested inside of a loop. You decide which loop structure is best to use.)
C++ code:
#include <iostream>
using namespace std;
int main(){
//initializing user_guess,guess_count and
number
int user_guess,guess_count,number;
//for getting different random values
srand(time(0));
//initializing
guess_count
guess_count=0;
//obtaining number from
1 to 500
number=1+rand()%500;
//asking to Guess a
number
cout<<"Guess a
number from 1 to 500: ";
//accepting
user_guess
cin>>user_guess;
//checking if number is
not equal to user_guess
while(number!=user_guess){
//if user_guess is low
if(user_guess<number){
//printing low
cout<<"Too low, try again.";
//incrementing guess_count
guess_count++;
}
//if user_guess is high
else if(user_guess>number){
//printing high
cout<<"Too high, try again.";
//incrementing guess_count
guess_count++;
}
//accepting user_guess
cin>>user_guess;
}
//printing number of
user_guess
cout<<"Correct,Number of guesses taken is
"<<guess_count<<endl;
return 0;
}
Screenshot:
Input and Output: