Site icon Study Algorithms

How to generate a random number in C?

This is one of the method, not everyone is aware of in C.
To generate a random number, C itself provides us a method srand().

We can use it in this way.

#include <stdio.h>
#include <time.h>

int main(void)
{
    srand(time(NULL));
    int r = rand();

    printf("Random number = %d", r);

    return 0;
}

NOTE: The function srand(time(NULL)) can only be called once in the program.

Exit mobile version