# How to Create a Random Number Generator in C++

2 min readIn this article, we’ll go over the functions needed to create a random number generator in C++. In the world of computers, random numbers form an essential component to add the flavor of anonymity and security.

A random number generator forms the backbone of creating pseudo-random numbers.

The idea behind pseudo-random numbers is that a computer does not have a thinking process to select a random number. So even though an output number produced may seem random, the values are mathematically computed.

## srand() and rand() functions

The srand() function in C++ can perform pseudo-random number calculation. This function requires a **seed value** which forms the basis of computation of random numbers.

srand(unsigned int seed_value)

With the help of the seed value, `srand()`

sets the stage for the generation of pseudo-random numbers by the `rand()`

function.

int random = rand();

And Voila! We have achieved the simple task of generating a random number. However, the hard part is to understand the concept behind the random number generators.

## Importance of a Seed Value

The seed value holds the key to the series of random numbers. The set of numbers calculated will be similar if the same seed value is provided to the function.

The default seed value for the `srand()`

function is `1`

, therefore a rand() function call without providing a fresh seed value will still fetch us a string of random numbers. The problem here is that every time you run the program with the seed value, the output will remain the same.

A simple solution to our problem is using a fresh seed value each time we run the program. What changes every second? – **Time**. We used the concept of the current timestamp being the current seed value.

You can create a timestamp by using:

time_t current_time = time(NULL);

The `current_time`

variable holds the number of seconds passed since January, 1970. This value is passed to the `srand()`

function and then we get a fresh sequence of pseudo-random numbers.

We can skip the initialization of timestamp to a variable and simply pass the timestamp to the function.

srand((unsigned) time(NULL));

The seed value is provided once in a program no matter how many random numbers are to be generated.

## Create the Perfect Random Number Generator in C++

The following code demonstrates the proper generation of a random number.

#include<iostream> #include<cstdlib> using namespace std; int main(){ // Providing a seed value srand((unsigned) time(NULL)); // Get a random number int random = rand(); // Print the random number cout<<random<<endl; return 1; }

Output:

1897776064

The number generated is too huge for proper usage in normal calculations.

## Generate random numbers within a range

There is a need to restrict the random numbers within a certain range. For this specific purpose, we use the modulus `%`

operator.

For instance, in order to generate random numbers from 0 to 9, we can use:

int random = rand() % 10;

Similarly, if we need to fetch random numbers from 1 to 9, we use:

int random = 1 + (rand() % 9);

The general equation can be stated as:

int random = offset + (rand() % range);

In the above equation:

**offset**– The starting point for the range of random numbers**range**– The number of values between first and the last possible random number including the limits.

For instance, in a set of random numbers between 10 – 100, we have offset as 10 and range as 91.

Let us run an example of a program that prints 5 random numbers between 100 and 200.

#include<iostream> #include<cstdlib> using namespace std; int main(){ // Providing a seed value srand((unsigned) time(NULL)); // Loop to get 5 random numbers for(int i=1; i<=5; i++){ // Retrieve a random number between 100 and 200 // Offset = 100 // Range = 101 int random = 100 + (rand() % 101); // Print the random number cout<<random<<endl; } return 1; }

**Output:**

144 175 162 137 200

To clarify, if no seed value is provided, the output for the above program will be the same every time we run it. Even though the random numbers within the set are different, the complete set will be identical.

## Applications of Random Number Generators (RNGs)

The power of random number generation may seem limited, but it is otherwise. Therefore, let us look at a few uses of RNGs.

**Cryptography**

Unpredictability is considered a measure of security in the field of cryptography. Therefore, there is significant use of Random Number Generators such as keys and nonces.

**Games**

The traditional games included dices and shuffling of cards to introduce randomness to the game, thereby, adding fun and uncertain results. Similarly, modern game development has a concept of pre- and post- randomness that adds an extra dimension to the game.

**Randomized Algorithm**

In these algorithms, there is a degree of randomness introduced to an already known algorithm. Most importantly, the purpose of these algorithms is to achieve better performance by trading-off the probability of success.

## Conclusion

The RNGs or PRNGs (Pseudo-Random Number Generators) are the building blocks of modern cyber-security and cryptography. The basic principle of these RNGs lie in some computation providing different numbers, that seem random.

We hope this article was understandable to the reader. Feel free to comment below for any queries or suggestions.

www.hello-android.com