Category: C++
Added: 5th of October 2021
Viewed: 1,512 times
Guess the random number C++ code on Ubuntu and Ubuntu based distributions, Learning C++
The following code asks the user to guess the random number between 1 and 10.
If the number is higher or lower than the random number, a message is displayed to the user
Once the user inputs the correct number, a message is displayed showing the user how many turns it took them to get the correct number
#include <iostream>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int random_number=rand() % 10 + 1;
int guess;
int turns=0;
turns=1;
cout << "Can you guess the random number between 1-10? ";
cin >> guess;
while (guess!=random_number)
{
if (guess < random_number)
{
cout << "Your guess is wrong. Enter a higher number? ";
}
if (guess > random_number)
{
cout << "Your guess is wrong. Enter a lower number? ";
}
turns++;
cin >> guess;
}
cout << "*** Congratulations, the random number was " << random_number << " ***" << endl;
cout << "*** It took you " << turns<< " turn(s) to get the correct number ***" << endl;
return 0;
}
Create a new file on your desktop named
guess_the_number.cpp and copy and paste the code above.
Next you need to compile the code by issuing the following command
g++ guess_the_number.cpp -o guess_the_number
Once compiled enter the following command in the terminal to execute the code
./guess_the_number
If this is your first time using C++ on Ubuntu or an Ubuntu based distribution, please visit the following link
https://www.mycomputertips.co.uk/197