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.
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; } |
7
Note : Output generated on each run may be different because number is generated randomly.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Generate a random permutation of elements from range [L, R] (Divide and Conquer)
- Select a random number from stream, with O(1) space
- C Program for Number of elements with odd factors in given range
- C/C++ Program to find Prime Numbers between given range
- C/C++ Program to Find the Number Occurring Odd Number of Times
- C/C++ Program for n-th Fibonacci number
- C/C++ Program for nth multiple of a number in Fibonacci Series
- Program to check if a number belongs to a particular base or not
- Program to convert given number of days in terms of Years, Weeks and Days
- C Program for Number of stopping station problem
- C Program to Print Number series without using any loop
- C++ Program to check Prime Number
- C Program to Check if all digits of a number divide it
- C/C++ Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- C Program to Find minimum sum of factors of number
- C Program for Find largest prime factor of a number
- C Program for Find sum of odd factors of a number
- C Program for efficiently print all prime factors of a given number
- C Program to check Armstrong Number
- C Program for Sum the digits of a given number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

