How to generate pseudo-random numbers in C

We can use the rand() and srand() functions to generate pseudo-random numbers in C.

In order to use these functions, you must include the <stdlib.h> library in the program.

These two functions are closely related to each other. Without the srand() function, the rand() function would always generate the same number each time the program is run. We will go over why this happens.

The srand() function

In order to generate a random number, the srand() function initializes the seedits argument that is a starting point, which is necessary to compute the output.

Syntax

The syntax of the srand() function is as follows:

void srand(unsigned int)

Parameters

The function needs an unsigned int as a mandatory value that will set the seed.

Note: Generally when using C, we use the Unix timestamp as the seed. This practice should be avoided when we need truly random numbers.

Return value

The function does not return anything.

The rand() function

The rand() function is used to generate a pseudo-random number in a certain range.

If rand() is used without specifying the seed (which is set by the srand() function), it is set to 11 by default.

Syntax

The syntax of the rand() function is as follows:

int rand(void)

Parameters

The function does not need any parameters.

Return value

The function will return a pseudo-random number in a certain range (from seed to RAND_MAX)

Note: RAND_MAX changes according to the compiler we use.

Code

Let’s see what happens if we want to generate a random number with a deterministic seed.

#include <stdio.h>
#include <stdlib.h>
int main(){
srand(55); // we set the seed here
int n = rand(); // now, lets generate a "random" number
printf("Pseudo-random number: %d\n", n); // print it
}

Here, we have a problem. Every time we run the program, it will always generate the same number.

To avoid this, we have to use another value as the seed, e.g., the UNIX timestamp (which will change every time we run the program).

We will use the time(0) function from the time.h library.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
srand(time(0)); // let's set the seed with unix timestamp
int n = rand();
printf("Pseudo-random number: %d\n", n);
}

The code example above will generate a new random number every time the code is run.