Write a 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.
//edited code in cpp
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
cout<<"I pulled a random number 1-100. Enter your guess\n";
srand(time(0)); //function required for rand function
int count =0;
int randomNumber=rand()%100 +1; //assigning a random integer between 0 and 100 to a
int userInput;
cin>>userInput; //taking input from user
count+=1;
while(userInput<1 || userInput>100) //checking if input number is less than 1 or greater than 100
{
cout<<"no is out of bound reenter no\n";
cin>>userInput;
}
if(userInput!=randomNumber)
{
if (randomNumber>userInput)
cout<<"higher\n";
else if (randomNumber<userInput)
cout<<"lower\n";
while(userInput!=randomNumber)
{
cin>>userInput;
count+=1;
if (randomNumber>userInput)
cout<<"higher\n";
else if(randomNumber<userInput)
cout<<"Lower\n";
}
}
if (userInput==randomNumber)
cout<<"Correct! You guessed my number in "<<count<<" tries";
}
Get Answers For Free
Most questions answered within 1 hours.