👋 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 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:

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

int main(void) {

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

  // 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 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.