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.
srand()
functionIn order to generate a random number, the srand()
function initializes the
The syntax of the srand()
function is as follows:
void srand(unsigned int)
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.
The function does not return anything.
rand()
functionThe 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.
The syntax of the rand()
function is as follows:
int rand(void)
The function does not need any parameters.
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.
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.