Method 1: Using the rand() Function

The rand() function is used to generate random numbers in C. It returns a random integer value that can further be scaled according to the range required

#include <stdio.h>
#include <stdlib.h>

int main() {
  int random_number = rand();
  printf("Random Number: %d\n", random_number);
  return 0;
}

Output: The value of the random number may not vary on each execution since the rand() function generates a pseudo-random number.

Method 2: Seeding with srand()

To ensure a different sequence of random numbers, the srand() function is used to seed the random number generator. It's commonly used at the current time as the seed.

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

int main() {
  srand(time(0));
  int random_number = rand();
  printf("Random Number: %d\n", random_number);
  return 0;
}

Output: The value of the random number will change with every execution, thanks to the seeding of the random number generator with the current time.

By using both rand() and srand(), one can generate random numbers efficiently in C, for various purposes.

Summary of Approaches

Using rand() Without Seeding (First Snippet)

Pros

Cons

Using rand() with Seeding (srand()) (Second Snippet)

Pros

Cons

In summary, using rand() without seeding might be useful in very specific cases where the same sequence is desired, but for most general purposes, using srand() to seed the random number generator is the preferable approach.

How to Generate Random Numbers in C Language