![]() |
VOOZH | about |
Write a C program to generate random numbers in a range.
Examples
Input: min = 5, max = 15
Output: 9, 11, 2
Explanation: Any integer between 5 and 15 can be the output.Input: min = 0, max = 100
Output: 42, 27, 11, 98
Explanation: Any integer between 0 and 100 can be the output.
We can use any of the given different methods to generate random within the given range in C:
Table of Content
Generating random numbers in C is useful in many applications. For those interested in exploring how randomness is applied in algorithms and data structures, the C Programming Course Online with Data Structures covers this topic extensively.
C does not have an inbuilt function for generating a number in the range, but it does have rand function which generates a random number from 0 to RAND_MAX. With the help of rand (), a number in the range can be generated using the modulo operator.
Random numbers between 5 and 7: 6 6 5 6 7 6 6 5 5 6
Time Complexity: O(N) where N is the count of random numbers to be generated
Auxiliary Space: O(1)
Note: Output generated on each run may not be different because the number is generated are based on the same seed. To modify the seed, we can use srand() with rand function or use rand_r().
The rand_r() function is a re-entrant version of rand() which takes a seed pointer as an argument. Providing different seeds each time allows users to avoid repetition of the same sequence of the random number.
Random numbers between 5 and 7: 7 6 6 6 5 6 6 7 6 6
Time Complexity: O(N) where N is the count of random numbers to be generated
Auxiliary Space: O(1)
The /dev/urandom is a special file in Unix-like systems that works as psuedo random number generators. Reading from this file can provide more randomness compared to rand().
Random numbers between 5 and 7: 3 3 7 4 7 4 5 5 7 5
Time Complexity: O(N) where N is the count of random numbers to be generated
Auxiliary Space: O(1)
Custom seed initialization involves using the current time or other unique values as a seed to ensure a different sequence of random numbers on each run. We them specify this unique seed value with the srand() function.
Random numbers between 5 and 7: 7 5 7 6 5 5 6 6 7 5
Time Complexity: O(N) where N is the count of random numbers to be generated
Auxiliary Space: O(1)
In this article, we have discussed several methods to generate random numbers in a range, including using the standard rand() function, its re-entrant version rand_r(), the Unix-like system's /dev/urandom file, and custom seeding techniques. Each method offers different advantages, from ease of use to increased randomness and control over the random number sequence. By understanding and selecting the appropriate method based on your specific needs, you can effectively generate random numbers within any desired range in C.