C++

What are rand() and srand() in C++

In the world of computers, random numbers are the necessary components that are required in multiple applications to produce games, or simulations as well as other applications that require random events, such as in dice games where users need random events. Because without having them, they will have the same side popping up every time they throw the dice. In the physical environment, users can have random events generated however it is not possible when it comes to the computer.

Quick Outline

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

In C++, a pseudo-random number generator enables users to produce random numbers. It is also known as a PRNG because computers understand binary “0” and “1” language. In simple words, it can be defined as a process that takes a starting number as a seed and changes it into some other number that is unlike a seed using mathematical operations.

Additionally, this operation is carried out repeatedly by taking the most recently generated number each time and these numbers are not related to the previous numbers. Therefore, this process can produce a series of random numbers.

Applications of Random Number Generator(PRNG)

There are multiple applications of random number generators, and some of the primary uses are listed below:

  • Game Development: The main use of random numbers can be seen in traditional games like coins, card shuffling, or dice. Likewise, modern game development introduced pre and post-randomness that adds more dimension to the game.
  • Cryptography: Random numbers are frequently utilized in cryptography as well as in cybersecurity.
  • Randomized Algorithm: For achieving better performance, randomized algorithms are used. Moreover, by using them, users can generate random jokes, quotes, or content on websites.

Main Functions of Random Number Generator(PRNG) in C++

In C++, there is a built-in pseudo-random number generator that provides two main functions. These functions are utilized for producing random numbers. These functions are:

  • rand() Function
  • srand() Function

What is rand() in C++?

In C++, the rand() is the built-in function that is utilized for producing random numbers in code. The generated numbers ranged from “0” to any maximum number(varied according to the user’s requirements). The rand() is included in the “<cstdlib>” header file. If users need to generate random numbers, they are required to include this header file at the start of their code.

Syntax of rand() Function in C++

The general syntax of the rand() function is provided below:

int rand();

Parameter
In C++, the rand() function does not accept any argument.

Return Value
The return value of this function is an integer number between “0” to any random highest number(RAND_MAX).

Exceptions
By using the rand() function, generated numbers will be in a similar sequence all over the program. This is the only exception scenario otherwise there is no exception in the rand() function.

Uses of rand() Function in C++

In C++, the major uses of the rand() function are provided below:

  • It is utilized for producing random numbers in the provided code because a computer just understands the zero and one.
  • It returns any integer number between “0” to the maximum random number as defined by the user.
  • It is used to generate the same sequence of random numbers for a particular range.

Let’s move ahead and check out the below-provided examples to understand the working of the rand() function!

Example 1: How to Produce Random Number Using rand() Function in C++?

To generate a random number by utilizing the rand() function without providing the seeding value, first, we added the required header files, such as “<iostream>” for input\output functionality and “<cstdlib>” for utilizing the rand() function. Next, we passed the rand() function to the integer type variable named “rnum”. Afterward, we added the “cout” stream to print the random number on the console:

#include<iostream>
#include
using namespace std;

int main()
{
  int rnum = rand();
  cout <<"Random Number is: "<< rnum;
}

As you can see, the random number has been displayed on the screen:

Example 2: How to Produce Same Sequence of Random Number Using rand() Function With C++ Loop?

In this example code, we will use the rand() function to generate the series of random numbers and whenever the code is executed, it will generate the same random numbers. In the below-provided code, we add the header files. Then, declare the integer type variable and use the first “cout” statement to display the message. Next, invoke the rand() function inside the “for” loop to show the same sequence of random number:

#include<iostream>
#include<cstdlib>

int main()
{
    int rnum;
    std::cout<<"Same Sequence of Random Numbers are: ";
    for(rnum=0; rnum< 5; rnum++)
        std::cout<<rand()<<"\n";
    return 0;
}

Output

Example 3: How to Produce Random Number Between 0 to RAND_MAX Using rand() Function in C++?

To generate a random number between “0” to the maximum integer value “RAND_MAX” using the “rand()” function, first of all, we add the required header files at the top of the coding file, such as “<cstdlib>” that includes the “rand()” function and “<iostream>” for accessing the input\output functionality. Then, we provide the “RAND_MAX” range of the “rand()” function that will return the maximum integer value between (32767) using the “cout” statement. Inside the output stream, we call the “static_cast<data_type>()” unary operator to convert one data type to another:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
  cout<< "Maximum Integer Value is: " << RAND_MAX << '\n'
        << "Random Number Between 0 to RAND_MAX is: "
        << static_cast(rand()) / RAND_MAX;
}

It can be seen that the above-given code first generated the maximum integer value then produced the random number between “0” to the maximum integer value “RAND_MAX”:

Note: As you noticed, we have executed the same code multiple times but the generated random value remains the same each time. In order to seed the “rand()” function for generating the different random numbers, the “srand(<argument>)” is used. For more understanding, let’s move forward to the next section.

What is srand() in C++?

In C++, the “srand()” function is the built-in function that is included in the “<cstdlib>” header file and used to set the initial point for generating a sequence of pseudo-random numbers. Basically, it sets the seed for the “rand()” function that is “1” by default which indicates that if the srand() function is not invoked before the rand() function then it behaves as if it was seeded with the “srand(1)”. Moreover, it makes the “rand()” function’s output random. Otherwise, that function output will remain the same every time it is invoked. Additionally, users need to invoke the “srand()” function just once before calling the “rand()” function instead of each time.

What is Seed Value in Random Numbers Generator in C++?

In random number generators, the seed value is the initial point for a sequence of pseudo-random numbers. In simple words, the seed value is the key that is used for getting a different output whenever users execute the random number generator in C++.

Syntax of srand() Function in C++

Here is the syntax of the “srand()” function in C++:

void srand(unsigned int seed);

Parameter
In C++, the srand() function accepts an integer value that can be utilized as seed by a pseudo-random number generator algorithm.

Return Value
None

Example 1: How to Generate Different Random Numbers Using rand() with srand() Function in C++?

To generate a different random number at each execution using the “rand()” function along with the “srand()” function in C++, first, include the necessary header files for the input\output stream, for accessing the rand() function and use the “srand()” function and seed with the random-number generator with current time so that the generated number will be different each time. Here, the “NULL” means that the value isn’t saved anywhere. Afterward, called the “rand()” function for generating random number inside the “cout” statement:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand((unsigned) time(NULL));
    cout <<"Different Random Number: "<< rand() << "\n";
    return 0;
}

Output

Example 2: How to Generate Random Numbers Within Different Ranges Using rand() with srand() Function in C++?

In this code example, first of all, we include the all required header files then invoke the “srand()” function and pass the “time(0)” as the seed to initialize the random number generator that will return the time value which varies every time and hence the pseudo-random number varies for each call. After that, use the “for” loop that will produce the first “10” random numbers between “1” to “60” and display on the console with the help of the “cout” statement:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
  srand((unsigned) time(0));
 
  cout << "Random Numbers Between 1 to 60 are: ";
  for(int x = 0; x < 10; x++)
  {
   int rNum = 1 + (rand() % 60);
    cout << rNum << "\n";
  }
}

The resultant output of the above-described code has been provided below:

Example 3: How to Generate Random Float Numbers Using rand() with srand() Function in C++?

In C++, to produce random float numbers by utilizing the “rand()” with the “srand()” function, we set the time seed to “NULL” which indicates that the value isn’t stored anywhere. After that, we declare the integer type variable. Then, use the “static_cast” unary operator to change the integer type data into “float”:

#include <cstdlib>
#include <iostream>
#include <ctime>

using namespace std;

int main() {
  srand((unsigned) time(NULL));
  int ranNum;
  for (ranNum = 0; ranNum < 6; ranNum ++) {
    cout << static_cast  (rand()) / static_cast <float>(RAND_MAX) <<endl;
  }
}

As a result, the random float number has been generated successfully:

Example 4: How to Generate Random Numbers Using Current Time as Seed for Random Number Generator in C++?

Here, we use the current time as a seed for generating a random number generator. For that particular purpose, first, we set the seed to “time(0)” and then use the output statement to print the provided seed. After that, use the loop to get the “6” random numbers:

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0));
    cout << "The Provided seed is = " << time(0) << endl;
    cout << "The Generated Random number Using Current Time is = " ;
    for (int i = 0; i < 6; i++)
     cout << rand() << " "<< endl;

    return 0;
}

Output

rand() Function vs srand() Function in C++

The “rand()” and “srand()” are the built-in functions in C++ and used for the same operation which is known as generating random numbers having a little bit of difference:

Let’s check out the following table to understand the difference between them:

rand() srand()
It is utilized for generating random numbers. Seeds the random number generator utilized by the rand() function.
It doesn’t accept any parameters. It takes the arguments that are utilized as a seed.
It is invoked multiple times as users need to generate random numbers. It is invoked only once to provide the random number generator as a seed.
It will return the sequence of random numbers whenever it is called. It will return nothing.

That’s all about the “rand()” and “srand()” functions in C++.

Bottom Line

In C++, the “rand()” is the built-in function that is utilized for producing random numbers ranging from “0” to any maximum number. However, the “srand()” function is also the built-in function that is used to set the initial point for generating a sequence of pseudo-random numbers. Both functions are included in the “<cstdlib>” header file. In this guide, we have discussed the “rand()” and “srand()” functions with examples.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.