In this tutorial, you will learn to generate random numbers within a range in C programming. But before that, you may go through the topic below if you do not know about the rand()
and srand()
function used in random numbers generation.
Here we will use srand() function provided in C to generate random numbers. The current time will be used to seed the srand() function.
C Program to generate random numbers within the range
Since the rand() will generate random numbers between 0 to max value, but instead of 0 we want to enter the lower range as well as the upper range so here is the trick we need to implement.
(upRange - lrRange + 1))
then add the lower range at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int lrRange, upRange, n; //Number of random number you want printf("Enter how many random numbers you want: "); scanf ("%d", &n); //initial number printf("Enter the lower range: "); scanf ("%d", &lrRange); //the last number for random range printf("Enter the upper range: "); scanf ("%d", &upRange); srand(time(0)); printf("\n%d random numbers are: ", n); for (int i = 0; i < n; i++) { int num = (rand() % (upRange - lrRange + 1)) + lrRange; printf("%d ", num); } return 0; } |
Output:
Enter how many random numbers you want: 7
Enter the lower range: 10
Enter the upper range: 50
7 random numbers are:
22 29 24 33 18 41 11
Again execute the program but this time entered for 10 random numbers, start from 1 and give upper range 7.
Enter how many random numbers you want: 10
Enter the lower range: 1
Enter the upper range: 7
7 random numbers are:
1 3 7 7 5 2 1 5 1 2
Notice that the program is repeating the number as you requested for 10 random numbers but the range is limited to 7 numbers. Hence the program repeats the number.