For working professionals
For fresh graduates
More
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.
srand() sets the seed value for rand(). Without srand(), rand() generates the same sequence every time the program runs.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // Seed based on current time
printf("Random Number: %d\n", rand());
return 0;
}
Random Number: 1736257313
RAND_MAX is a constant that represents the maximum value rand() can return, typically 32767.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("RAND_MAX value: %d\n", RAND_MAX);
return 0;
}
RAND_MAX value: 32767
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int min = 10, max = 50;
srand(time(NULL));
int randomNum = min + rand() % (max - min + 1);
printf("Random Number in range %d-%d: %d\n", min, max, randomNum);
return 0;
}
Random Number in range 10-50: 27
rand() is not cryptographically secure. Instead, use OpenSSL’s RAND_bytes().
#include <openssl/rand.h>
#include <stdio.h>
int main() {
unsigned char buffer[4]; // 4 random bytes
RAND_bytes(buffer, sizeof(buffer));
printf("Secure Random Number: %u\n", *(unsigned int*)buffer);
return 0;
}
Secure Random Number: 312485239
rand() is not thread-safe. Instead, use rand_r() or Mersenne Twister.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *generateRandom(void *seed) {
unsigned int *threadSeed = (unsigned int *)seed;
printf("Thread-safe Random Number: %d\n", rand_r(threadSeed));
return NULL;
}
int main() {
pthread_t thread1, thread2;
unsigned int seed = time(NULL);
pthread_create(&thread1, NULL, generateRandom, &seed);
pthread_create(&thread2, NULL, generateRandom, &seed);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Thread-safe Random Number: 106761346
Thread-safe Random Number: 1763517814
The Mersenne Twister (mt19937) provides better randomness and a longer period (2¹⁹⁹³⁷-1).
#include <iostream>
#include <random>
using namespace std;
int main() {
mt19937 rng(time(NULL)); // Mersenne Twister
cout << "Mersenne Twister Random Number: " << rng() % 100 << endl;
return 0;
}
Mersenne Twister Random Number: 83
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Random Float: %f\n", (double)rand() / RAND_MAX);
return 0;
}
Random Float: 0.692547
Calling srand(time(NULL)) inside a loop may result in repeating values.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
for (int i = 0; i < 5; i++) {
srand(time(NULL)); // Reseeding too frequently
printf("%d\n", rand());
}
return 0;
}
13579
13579
13579
13579
13579
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 5; i++) {
printf("%d\n", rand());
}
return 0;
}
13579
24680
98765
54321
12345
Use /dev/random or /dev/urandom on Linux.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("/dev/urandom", "r");
int num;
fread(&num, sizeof(int), 1, fp);
fclose(fp);
printf("Random Number from /dev/urandom: %d\n", num);
return 0;
}
Random Number from /dev/urandom: 1947238491
This happens when srand() is not used or the seed is constant.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Random Number: %d\n", rand());
return 0;
}
Random Number: 41
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // Different sequence each run
printf("Random Number: %d\n", rand());
return 0;
}
Random Number: 98347561
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.