In: Computer Science
Write a program in C++ that generates a random number between 1 and 10 and asks the user to guess it. Your program should continue until the user guesses the correct number. With each guess the user makes the program tells the user if the guess is too high or too low.
To generate a random number between 1 and 10 you need the following code:
/* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ secretnumber = rand() % 10 + 1;
You also need to add these lines to the top of your program with the other <include> statements so you can use the time() function:
#include <time.h> #include <stdlib.h> #include <stdio.h>
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num, guess, tries = 0;
srand(time(0)); //seed random number generator
num = rand() % 100 + 1; // random number between 1 and 100
cout << "Guess the number"<<endl;
do
{
cout << "Enter a guess between 1 and 100 : ";
cin >> guess;
tries++;
if(guess<0 ||
guess>100){
cout<<"Invalid guess. Guess must be between 1 and
100"<<endl;
}else if (guess > num)
cout << "Too high, try again!\n\n";
else if (guess < num)
cout << "Too Low, try again!\n\n";
else
cout << "\nCorrect! You got it in " << tries << " guesses!\n";
} while (guess != num);
cin.ignore();
cin.get();
return 0;
}