Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Generating random number in a range in C

  • Difficulty Level : Easy
  • Last Updated : 23 Apr, 2018

How to generate a random number in a given range in C.

Examples:

We provide nothing but the best curated videos and practice problems for our students. Check out the C Foundation Course and master the C language from basic to advanced level. Wait no more, start learning today!
Input : Lower = 50,
        Upper = 100,
        Count of random Number = 5 
Output : 91 34 21 88 29 
Explanation: lower is the lower limit of the 
range and upper is the upper limit of the range.
Output contains 5 random numbers in given range.

As C does not have an inbuilt function for generating a number in the range, but it does have rand function which generate a random number from 0 to RAND_MAX. With the help of rand () a number in range can be generated as num = (rand() % (upper – lower + 1)) + lower




// 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 [lower, upper].
void printRandoms(int lower, int upper, 
                             int count)
{
    int i;
    for (i = 0; i < count; i++) {
        int num = (rand() %
           (upper - lower + 1)) + lower;
        printf("%d ", num);
    }
}
  
// Driver code
int main()
{
    int lower = 5, upper = 7, count = 1;
  
    // Use current time as 
    // seed for random generator
    srand(time(0));
  
    printRandoms(lower, upper, count);
  
    return 0;
}
Output:
7

Note : Output generated on each run may be different because number is generated randomly.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!