Open In App

Generating Random Numbers in a Range in C

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

Output
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().

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;
}

Output
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)

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;
}

Output
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)

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;
}

Output
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)

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:




Next Article

Similar Reads