c++ program. Write a program that generates a random number between 1 and 100 an
ID: 3832459 • Letter: C
Question
c++ program.
Write a program that generates a random number between 1 and 100 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. rand() in cstdlib.h generates a random number between 0 and a large integer number. Call srand(time(0)) just once at the beginning of the main to generate a different sequence of random numbers in every run.
rand() in cstdlib.h generates a random number between 0 and a large integer number. Call srand(time(0)) just once at the beginning of the main to generate a different sequence of random numbers in every run.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int num; num = rand() % 100 + 1; //num gets some random number between 1 and 100
.....
}
Explanation / Answer
// C++ code
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
srand(time(0));
int num;
num = rand()%100 + 1; // num gets some random number between 1 and 100
cout << "Guess the number from 1 to 100" << endl;
int guess;
while(1)
{
cout << "Enter your guess: ";
cin>>guess;
if(guess == num)
{
cout << "Congratulations.CORRECT GUESS!" << endl;
break;
}
else if(guess > num)
{
cout<<"Too high. try again. ";
}
else
{
cout<<"Too low. try again ";
}
}//end while
return 0;
}
/*
output:
Guess the number from 1 to 100
Enter your guess: 34
Too high. try again.
Enter your guess: 23
Too low. try again
Enter your guess: 30
Too low. try again
Enter your guess: 31
Too low. try again
Enter your guess: 32
Too low. try again
Enter your guess: 33
Congratulations.CORRECT GUESS!
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.