👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.

How to pick a random number in C?

In C, the int rand() function returns a pseudo-random number between 0 and RAND_MAX. RAND_MAX is a constant defined in stdlib.h, its value may vary according to the compiler. Here is a complete example:

#include <stdio.h>  // For printf()
#include <stdlib.h> // For srand() and rand()
#include <time.h>   // For time()

int main(void) {

  // Set the generator seed (set it once)
  // This prevent from always generating the same numbers
  srand(time(NULL));

  // Pick two pseudo-random numbers
  printf ("First random number: %d\n", rand());
  printf ("Second random number: %d\n", rand());
  return 0;
}

Note: to prevent the generator from always returning the same numbers, we generally initialise the seed with srand(). The seed is defined with the current time that is always changing, modifying the sequence of random numbers. If the seed is not set, the numbers will always be the same.

srand(time(NULL));


Related questions:

More