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
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 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_MAXchanges 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 hereint n = rand(); // now, lets generate a "random" numberprintf("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 timestampint 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.