Generating Random Numbers in a Range in C
Last Updated :
11 Oct, 2024
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.
Different Ways to Generate Random Numbers in a Range in C
We can use any of the given different methods to generate random within the given range in C:
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.
1. Generate Random Numbers in a Range Using rand()
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.
- Use rand() to generate a random number rd_num.
- Shift the number to fit within the range [min, max] using the formula: rd_num= (rd_num % (max- min + 1)) + min.
Program to Generate Random Numbers in a Range Using rand() Function
C
// C program for generating a
// random number in a given range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generates and prints 'count' random
// numbers in range [min, max].
void printRandoms(int min, int max, int count) {
printf("Random numbers between %d and %d: ", min, max);
// Loop that will print the count random numbers
for (int i = 0; i < count; i++) {
// Find the random number in the range [min, max]
int rd_num = rand() % (max - min + 1) + min;
printf("%d ", rd_num);
}
}
int main() {
int min = 5, max = 7, count = 10;
printRandoms(min, max, count);
return 0;
}
OutputRandom 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().
2. Generate Random Numbers in a Range Using 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.
- Create a variable seed to take current time (using time(0)) as the seed.
- Use rand_r() to generate a random number rd_num with address of seed as an argument.
- Shift the number to fit within the range [min, max] using the formula: rd_num= (rd_num % (max- min + 1)) + min.
Program to Generate Random Numbers in a Range Using rand_r()
C
// C Program to generate a random number in a given
// range using rand_r()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printRandoms(int min, int max, int count) {
printf("Random numbers between %d and %d: ", min, max);
// Taking current time as seed
unsigned int seed = time(0);
for (int i = 0; i < count; i++) {
// Generate a random number in the range [min, max]
int rd_num = rand_r(&seed) % (max - min + 1) + min;
printf("%d ", rd_num);
}
}
int main() {
int min = 5, max = 7, count = 10;
printRandoms(min, max, count);
return 0;
}
OutputRandom 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)
3. Generate Random Numbers in a Range Using “/dev/urandom”
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().
- Include the necessary headers: <fcntl.h> and <unistd.h>
- Open /dev/urandom and read random bytes using read() function into the variable rd_num
- Scale it to fit within the range [min, max].
Program to Generate Random Numbers in a Range Using “/dev/urandom”
C
// C Program to generate a random number in a given range using /dev/urandom
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
void printRandoms(int min, int max, int count) {
// Open the file urandom
int fd = open("/dev/urandom", O_RDONLY);
// Print the random number
printf("Random numbers between %d and %d: ", min, max);
for (int i = 0; i < count; i++) {
// Generate a random number
int rd_num;
read(fd, &rd_num, sizeof(rd_num));
// Scale the random value to the range [min, max]
rd_num = rd_num % (max - min + 1) + min;
printf("%d ", rd_num);
}
// close the file
close(fd);
}
int main()
{
int min = 5, max = 7, count = 10;
printRandoms(min, max, count);
return 0;
}
OutputRandom 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)
4. Generate Random Numbers in a Range Using Custom Seed
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.
- Use the time(0) to provide the current time as the custom seed for the srand() function.
- Use rand() to generate a random number.
- Scale the number to fit within the range [min, max].
Program to Generate Random Numbers in a Range Using Custom Seed
C
// C program for generating a random number in a given
// range with custom seed
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generates and prints 'count' random
// numbers in range [min, max].
void printRandoms(int min, int max, int count) {
// Setting seed for the rand() function
srand(time(0));
printf("Random numbers between %d and %d: ", min, max);
// Loop that will print the count random numbers
for (int i = 0; i < count; i++) {
// Find the random number in the given range
// Generate a random number in the range [min, max]
int random_number = rand() % (max - min + 1) + min;
printf("%d ", random_number);
}
}
int main() {
int min = 5, max = 7, count = 10;
printRandoms(min, max, count);
return 0;
}
OutputRandom 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)
Conclusion
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.
Related Articles:
Similar Reads
How to Find the Range of Numbers in an Array in C?
The range of numbers within an array is defined as the difference between the maximum and the minimum element present in the array. In this article, we will learn how we can find the range of numbers in an array in C. Example Input:int arr[] = { 23, 12, 45, 20, 90, 89, 95, 32, 65, 19 }Output: The ra
2 min read
C Program To Find Prime Numbers Between Given Range
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, and 11 are prime numbers. In this article, we will learn how to find all the prime numbers between the given range. Example Input: l = 10, r = 30Output: 11 13 17 19Explan
6 min read
C Program for Number of elements with odd factors in given range
Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
2 min read
Number guessing game in C
Given an integer N. A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end after 10 attempts and if the player failed to guess the number, and then he loses the game. Examples: N = 100Number chosen: 2
2 min read
Converting String to Long in C
Here, we will see how to build a C Program For String to Long Conversion using strtol() function. Syntax: long int strtol(char *string, char **ptr, int base)The first argument is given as a stringThe second argument is a reference to an object of type char*The third argument denotes the base in whic
4 min read
C program to Count the digits of a number
Given a number N, write a C program to find the count of digits in the number N. Examples: Input: N = 12345 Output: 5 Explanation: The count of digit in 12345 = 5 Input: N = 23451452 Output: 8 Explanation: The count of digits in 23451452 = 8Methods to Count Digits of a NumberThere are a few methods
4 min read
Reverse Number Program in C
The reverse of a number means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C programming language. For example, if number num = 12548, the reverse of number num is 84521. Algorithm to Reverse an IntegerInput: num (1) Initialize re
2 min read
CÂ Program to Print Prime Numbers From 1 to N
Prime numbers are positive integers greater than 1 that have no divisors other than 1 and themselves. In this article, we will learn to generate and display all prime numbers from 1 to N in C programming language. AlgorithmCheck every number from 1 to N whether it is prime by using isPrime() functio
2 min read
C Program to Generate Multiplication Table
In this article, we are creating a multiplication table in c which is a basic program for printing tables in c. We are printing multiplication tables of the number up to a given range. We will use the concepts of looping and using a 2-D array to print a Multiplication Table. Multiplication TableA mu
4 min read
How to Convert an Integer to a String in C?
Write a C program to convert the given integer value to string. Examples Input: 1234Output: "1234"Explanation: The integer 1234 is converted to the string "1234". Input: -567Output: "-567"Explanation: The integer -567 is converted to the string "-567". Different Methods to Convert an Integer to a St
4 min read