Guessing the number program in C++

We use to generate a random number and we then use to use to guess the number. We will learn about srand and rand function in C++

We will use srand and rand functions in C++. Complete explanation to srand and rand function is provided. We will generate a random number between 1 to 9. And then will provide the user 3 chances to guess it.

We first include iostream, ctime, and stdlib.

Now we create a function random_number_generator()

In random_number_generator we will provide time(nullptr) to srand. The time(nullptr) will give a value 0.

srand :- This function is used to seed random numbers generated by the rand function. When we use the rand function multiple times to generate multiple random numbers, the same number should not be generated consecutively. To get the different number whenever use rand function we use srand function.

Now srand function requires the time interval to seed (change) the random number. So in this program, the time function to get the time interval. We provide time function nullptr which gives a time interval as 0.

rand:-We use this function to generate a random number.

Now we store the random number in the random_number variable. We have random_number=rand()%max+min. This means the random number is generated is taken the modular division with the max number will provide the remainder that is less than max and then we add min to it for getting the range of random number between min and max.

Now in the main function, we call the random_number_generator function and for providing 3 chances, we use the do-while loop and in the do statement we take the guessed_number from the user. Then compare that number with a random number and show the result.

int random_number_generator()
{
int random_number;
int min{1};
int max{9};

srand(time(nullptr));

{
random_number= rand()%max + min;
}
return(random_number);
}

Output or test run is provided in the image below

Complete source code is provided as a Zip file.