Category: C++

Added: 5th of October 2021

Viewed: 157 times

Guess the random number C++ code on Ubuntu and Ubuntu based distributions, Learning C++

This tutorial works in Ubunbu, Kubuntu, Xubuntu, Lubuntu, Ubuntu Mate and other Ubuntu based distributions. The tutorial also works in Linux Mint and other Debian based distributions.

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

Other Tips & Tutorials

C++

Guess the random number C++ code on Ubuntu and Ubuntu based distributions, Learning C++

Posted: 5th of October 2021

Views: 157

C++

Basic user input and output using C++ in Linux, Learning C++

Posted: 19th of December 2020

Views: 697

C++

Install Microsoft Visual Studio Code in Kubuntu, Ubuntu and Ubuntu based distributions. Compile and execute C++ script

Posted: 18th of October 2020

Views: 871

C++

Create a simple c++ script using Ubuntu and other Ubuntu based distributions, Learning C++

Posted: 17th of October 2020

Views: 728