 A random number generator in C++ is used to generate a random number using a code. It is a great way to add anonymity and security to the C++ programming world. The idea is to randomly select any number from a specified range and display it on the console. In this article, you will explore everything about a random number generator in C++, along with a few examples.

## What are Random Number Generators Used For?

Consider this example, you are creating a game of dice. Will the game be possible if the same number shows up every time you roll the dice? Of course not. That’s where random number generators come into the picture. They can create random events and display a random number from a specified range of values.

With the element of randomness, you can create the dice game code and many more such programs that require generating random numbers. However, a programming language or a computer cannot create pure random numbers. Hence, C++ and other programming languages use pseudo-random number generators.

## What is a Pseudo-Random Number Generator (PRNG) in C++?

A pseudo-random number generator is a simulator of a random number generator in C++. This means that the pseudo-random number generator allows you to create a sense of randomness in C++. It is called a PRNG because everything in computers is binary that is 0 and 1. Hence, generating random events in computers is not possible.

When the pseudo-random number generator uses mathematical operations, it ensures that the new value is not similar to the seed value. With this, the program can generate numbers that seem to be random. C++ comes with an in-built pseudo-random number generator that provides two functions: rand() and srand() for the random number generation in C++.

#### Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE Courses ## Rand and Srand Functions in C++

Rand and srand are two predefined functions to help with random number generators in C++. Here are the prototypes, parameters, return values, descriptions, and examples of both functions.

### Rand()

• Prototype: int rand();
• Parameters: Does not have any parameters
• Return Value: Returns an integer value between 0 and RAND_MAX
• Description: This function generates and returns the next random number between 0 and RAND_MAX, a constant value described in the <cstdlib> header file and set to 32767
• Example: We will use the rand() function in C++ to generate a random number in this example

#include <cstdlib>

#include <iostream>

using namespace std;

int main() {

int randomNumber = rand();

cout << randomNumber << endl;

}

#### Output: #### Output: As you can see, the outputs are the same for both executions. You will understand the reason behind it later in this article.

### Srand()

• Prototype: void srand(unsigned int seed);
• Parameters: An integer value that defines the seed (initial value) used by the pseudo-random number generator in C++
• Return Value: None
• Description: The srand() function initializes the range or sequence of the pseudo-random numbers by passing the seed value. When you give the seed value using the srand() function, it will start the random number generator in C++ from that point. This seed value makes the output look random. Without the value, the output of the rand() function will always be the same whenever we run the program
• Example: For this example, you will use the srand() function and pass system time as the seed value to generate different output on every execution

#include<iostream>

#include<cstdlib>

using namespace std;

int main(){

// Using system time as a seed value

srand((unsigned) time(NULL));

int my_rand = rand();

// Printing the output

cout<<my_rand<<endl;

return 0;

}

#### Output: #### Output: As you can see in the outputs, the result was different both times.

## Importance of the Seed Value in Random Number Generator in C++

The seed value is the key to getting a different output each time you run the random number generator in C++. Since the pseudo-random number generator performs mathematical operations, the output will be the same if the seed value remains the same. Hence, the output for both executions was the same when you used only the rand() function, without providing a seed value.

The solution to getting a new output is to use fresh seed each time. The best solution to this is using system time as the seed value. That’s because the time changes every second. Hence, you have used the time as the seed value in the previous example to get a different output each time.

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

Now, you will create a perfect random number generator in C++ using the system time as seed value just like you did for the srand() function. But this time, you will use both srand and rand functions to create a set of different values each time you run the program.

#include <stdio.h>

#include <stdlib.h>

#include<time.h>

int main(void){

// Using current system time as seed value

srand(time(0));

for(int x = 0; x<3; x++)

printf(" %d ", rand());

return 0;

}

#### Output: #### Output: ## Using Random Number Generator in C++ to Generate Random Float

The rand() function returns a sequence of values. You can use type cast the sequence to generate a random float or double. The following example demonstrates the same by generating a random float between 2.2 and 4.4.

#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;

int main(){

srand(time(0));  // Initialize random number generator.

cout<<"Random float number generated between 2.2 and 4.4:"<<endl;

cout<<2.2 + static_cast <float> (rand()) / ( static_cast <float> (RAND_MAX/(4.4-2.2)));

return 0;

}

#### Output: ## How to Generate Random Numbers Between 0 and 1 Using a Random Number Generator in C++?

You can use the rand() and srand function to generate numbers between 0 and 1. Since the numbers between 0 and 1 will be in decimals, you must cast the result to either float or double, just like you did in the previous example. If you don’t typecast the result, it will be converted to an integer; hence, the output will be 0. The following code generates a set of three random numbers between 0 and 1.

#include <time.h>

#include <iostream>

using namespace std;

int main(){

cout<<"Random numbers between 0 and 1:"<<endl;

srand( (unsigned)time( NULL ) );

for (int x = 0; x < 3; x++)

{

// Type casting the result to float

cout << (float) rand()/RAND_MAX << endl;

}

return 0;

}

#### Output: ## How to Generate Random Numbers Between 1 and 10?

You can also use a random number generator in C++ to generate numbers between 1 and 10. You can do this using the modulus operator. The following program shows the use of a modulus operator to generate random numbers between 1 and 10.

#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;

int main(){

// Initializing random number generator in C++

srand(time(0));

cout<<"Random numbers between 1 and 10:"<<endl;

for(int x=0;x<5;x++)

cout << 1+ (rand() % 10) <<"\n";

return 0;

}

#### Output: ## How to Generate Random Numbers in C++ Within a Range

Similar to 1 and 10, you can generate random numbers within any range using the modulus operator. For instance, to generate numbers between 1 and 100, you can write int random = 1+ (rand() % 100). You can represent the general syntax of the equation as:

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

In the above syntax:

• offset: Defines the starting point of the range
• range: The number of possible values between the start and end of the range with both numbers inclusive. For instance, for the range between 100 to 300, the offset will be 100, and the range will be 201.

Now, look at an example to generate random numbers between the range 100 to 300, as mentioned above. You will use the for loop in C++ to generate ten random numbers between the given range.

#include<iostream>

#include<cstdlib>

using namespace std;

int main(){

srand((unsigned) time(NULL));

// Using for loop

for(int x=0; x<10; x++){

// Offset 100 and range 201 to generate random numbers between 100 and 300

int random = 100 + (rand() % 201);

cout<<random<<"   ";

}

return 1;

}

#### Output: #### Full Stack Web Developer Course

To become an expert in MEAN Stack ## Applications of Random Number Generators in C++

You might wonder why you would need to generate random numbers, except for a while creating dice games? But there are several applications of random number generators. Some of the primary applications are:

### Games

As you have already seen at the beginning of the article, random number generators are vital in some games, such as the dice game. Besides the dice games, you can also use it in other games that require randomness. For instance, you can use it to create card games to distribute random cards or quiz games to ask unique questions every time.

### Cryptography

Besides the games, you can also use the C++ random number generator for security purposes. Randomness and anonymity are considered crucial in cryptography and other forms of security. You can use random number generators to create keys and nonces.

### Randomized Algorithms

Randomizing algorithms is adding the element of randomness to already defined algorithms. This is done to increase the performance and get better results by trading off success probability.

## What is the Difference Between Rand() and Srand()?

There are many differences between rand() and srand() functions. The table illustrated below defines some of the significant differences between the two.

### srand()

Function to generate a random number

Seeds the random number generator in C++

Called as many times as you want to generate the random numbers

Called only once to seed the random number generator

Does not accept an argument

Accepts an integer value that is used as the seed

Returns sequence of random numbers

Returns nothing

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

## Wrapping up

In this article, you have learned about random number generators in C++. You can now use the rand() and srand() functions to generate random values and put them to use in multiple applications such as games, cryptography, and randomized algorithms. Now that you know everything about the C++ random number generator, it’s time to learn about the other fundamentals of C++ programming.

You can refer to Simplilearn’s C++ Tutorial for Beginners. The tutorial covers basic concepts such as for loop and array to get a good grasp on the fundamentals. If you want to hone your programming skills, you can head to our SkillUp platform. The platform offers several free courses to help you learn, grow, and become familiar with numerous development languages, including C++.

You can also opt for the Full-Stack Web Development Course if you are looking to pursue a career in the development field. The course provides several hours of self-paced learning materials and applied learning. You will also get a certificate upon completing the course to improve the chances of landing a lucrative job proposal. To put it simply, the course is well adept at helping you excel in the web development field.

Have any questions for us? Leave them in the comments section, and our experts will answer them for you as soon as possible! Simplilearn