Write a c++ program to pull a random number between 1-100
inclusive. Ask the user to guess the number. If the random number
is higher than the guess, print "Higher". If the random number is
less than the guess, print "Lower". If the random number is equal
to the quess, print "Correct!".
Create a variable to count the number of guesses and intitialize it
to zero.
int guesses=0;
Increase this variable by 1 every time the user enters a new guess.
Print the number of guesses at the end.
eg:
I pulled a random number 1-100. Enter your guess:
50
Lower
20
Higher
25
Correct! You guessed my number in 3 tries.
Below is your answer:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//seeding to generate random number correct always
srand( time(NULL) );
//generate random number, formula is as below
//(rand() % (higher - lower + 1) + 1)
int random = (rand() % (100 - 1 + 1)) + 1;
//intitialize gues count
int guesses=0;
//initial prompt
cout<<"I pulled a random number 1-100. Enter your guess: "<<endl;
int num;
//loop to get the number from console
do {
cin>>num;
//increment guess
guesses++;
//check if lower or higher
if(num < random) {
cout<<"Lower"<<endl;
} else if(num > random){
cout<<"Higher"<<endl;
}
} while(num != random);//finish loop when number is guessed
//printing the result
cout<<"Correct! You guessed my number in "<<guesses<<" tries."<<endl;
return 0;
}
Output
Get Answers For Free
Most questions answered within 1 hours.