Facebook PixelHow to Generate Random Numbers in C Language | Blog | CodeWithHarry
How to Generate Random Numbers in C Language

How to Generate Random Numbers in C Language

"A comprehensive guide to generating random numbers in C using the rand() and srand() functions, with examples and output."

By CodeWithHarry

Updated: 5 April 2025

In the C programming language, random numbers can be generated primarily using two functions like rand() and srand().

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

  • Simple and straightforward to use.
  • Useful if you need a deterministic sequence of random numbers across different runs of the program.

Cons

  • Without seeding, the same sequence of random numbers will be generated every time the program is run.

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

Pros

  • By seeding with the current time, the random number generator produces different sequences of random numbers on each execution.
  • Applicable in most scenarios where random numbers are required.

Cons

  • The randomness is still pseudo-random, and it might not be suitable for cryptographic purposes.
  • Seeding with the current time might lead to the same sequence if the program is executed quickly in succession.

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.

Tags

crandomnumbersguide