# Generating random number in a range in C

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

```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.```

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 range can be generated as num = (rand() % (upper – lower + 1)) + lower

## C

 `// C program for generating a ` `// random number in a given range. ` `#include ` `#include ` `#include `   `// 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`

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 be different because the number is generated randomly.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next