For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
The random number generator in C plays a crucial role in various applications, from gaming to security. Whether you’re creating dice rolls, lottery games, or encryption keys, understanding how randomness works in C is essential. In addition, random number generator in C is so important, that every top-tier software development course focus on this particular topic.
In this guide, we'll also explore different ways to generate random numbers in C, covering everything from the basics to advanced techniques. You'll also find unique code examples, their outputs, and a detailed breakdown of each one.
C does not have a true random number generator—instead, it provides functions to generate pseudo-random numbers. This means the numbers appear random but follow a predictable sequence based on a starting value (seed).
The most common functions used in C for generating random numbers are:
By default, rand() produces the same sequence of numbers each time you run the program unless you seed it with a unique value. Let’s see this in action.
You can try and test this code on any of your machine with the compatible IDEs. However, for Linux-based system, you need to follow specialized C compiling instructions, otherwise it can create additional complexities.
Once, you’re ready with your IDE, just copy and paste the code to see its functionality in real-time. Rest, go through the explanation to understand how random number generator in C is working at its core.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Random numbers without seeding:\n");
for(int i = 0; i < 5; i++) {
printf("%d\n", rand());
}
return 0;
}
Output: (Same every time you run it)
1804289383
846930886
1681692777
1714636915
1957747793
Explanation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // Seed based on the current time
printf("Random numbers with seeding:\n");
for(int i = 0; i < 5; i++) {
printf("%d\n", rand());
}
return 0;
}
Output: (Different every time you run it)
1289473104
987343102
1348172312
874902347
2039481258
Explanation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int lower = 10, upper = 50;
printf("Random numbers between %d and %d:\n", lower, upper);
for(int i = 0; i < 5; i++) {
printf("%d\n", (rand() % (upper - lower + 1)) + lower);
}
return 0;
}
Output:
23
49
34
17
42
Explanation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
printf("Random floating-point numbers between 0 and 1:\n");
for(int i = 0; i < 5; i++) {
printf("%.4f\n", (double)rand() / RAND_MAX);
}
return 0;
}
Output:
0.4573
0.8291
0.2156
0.9823
0.3728
Explanation:
Feature | rand() | srand() |
Purpose | Generates a pseudo-random number | Sets the seed for rand() |
Needs Seeding? | No (but will always give the same numbers) | Yes (to change output each run) |
Affects Random Sequence? | No | Yes |
Output Consistency | Same sequence every execution | Different sequence if seeded uniquely |
Default Seed Value | System-dependent, often set to 1 | Needs to be explicitly defined |
Usage Frequency | Can be used multiple times | Typically used once per program execution |
Works Alone? | Yes | No, needs rand() to generate numbers |
Used in Cryptography? | No, not secure | No, but can improve randomness slightly |
Requires Additional Libraries? | No, included in <stdlib.h> | No, but <time.h> is often needed for time(NULL) seeding |
Suitable for Games? | Yes, but should be seeded | Yes, as it ensures varying outputs |
Suitable for Machine Learning? | No, lacks sufficient randomness | No, better alternatives like random() exist |
To ensure optimal randomness and avoid common pitfalls, follow these best practices when using random number generator in C.
srand(time(NULL)); // Seeds the generator with the current time
#include <openssl/rand.h>
unsigned char buffer[16];
RAND_bytes(buffer, sizeof(buffer));
int randomInRange = min + (int)((double)rand() / (RAND_MAX + 1) * (max - min + 1));
double randomValue = (double)rand() / RAND_MAX;
#include <random>
std::mt19937 rng(time(NULL));
int randomNum = rng() % 100;
If running a simulation multiple times, ensure that different seeds are used for each run to avoid identical outputs.
The random number generator in C is a powerful tool when used correctly. By understanding rand(), srand(), and how to scale values, you can generate numbers for various applications efficiently. Always follow best practices and avoid common pitfalls to ensure better randomness.
Now you know how to use the random number generator in C effectively. Try the code snippets and see the randomness in action.
A random number generator in C refers to functions like rand() that generate pseudo-random numbers—numbers that appear random but are actually determined by an algorithm. Since rand() follows a predictable sequence based on a seed value, the numbers aren’t truly random but pseudo-random. A random number generator in C refers to functions like rand() that generate pseudo-random numbers —numbers that appear random but are actually determined by an algorithm. Since rand() follows a predictable sequence based on a seed value, the numbers aren’t truly random but pseudo-random .
srand() sets the seed value for rand(). Without srand(), rand() generates the same sequence every time the program runs. srand() sets the seed value for rand(). Without srand(), rand() generates the same sequence every time the program runs. Example: #include
RAND_MAX is a constant that represents the maximum value rand() can return, typically 32767. RAND_MAX is a constant that represents the maximum value rand() can return, typically 32767 . Example: #include
Example: Generating a random number between min and max #include
rand() is not cryptographically secure. Instead, use OpenSSL’s RAND_bytes(). rand() is not cryptographically secure . Instead, use OpenSSL’s RAND_bytes(). Example (Secure random number using OpenSSL): #include
rand() is not thread-safe. Instead, use rand_r() or Mersenne Twister. rand() is not thread-safe . Instead, use rand_r() or Mersenne Twister . Example (Using rand_r() in a multi-threaded environment): #include
The Mersenne Twister (mt19937) provides better randomness and a longer period (2¹⁹⁹³⁷-1). The Mersenne Twister (mt19937) provides better randomness and a longer period ( 2¹⁹⁹³⁷-1 ). Example (Using Mersenne Twister in C++): #include
Example: Generating a float between 0 and 1 #include
Calling srand(time(NULL)) inside a loop may result in repeating values. Calling srand(time(NULL)) inside a loop may result in repeating values . Incorrect Example (Repetitive values): #include
Use /dev/random or /dev/urandom on Linux. Use /dev/random or /dev/urandom on Linux . Example: #include
This happens when srand() is not used or the seed is constant. This happens when srand() is not used or the seed is constant. Example (No seed, repetitive sequence): #include
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published