rand() in C
Last Updated :
03 Nov, 2023
The rand() function in the C programming language is used to generate pseudo-random numbers. It is used in C to generate random numbers in the range 0 to RAND_MAX.
The rand() function is part of the standard C library <stdlib.h> so to use this function, we need to include the <stdlib.h> library.
Syntax of rand()
int rand(void)
Parameters
- This function does not take any parameters.
Return Value
- This function returns the value between 0 and RAND_MAX where RAND_MAX is the macro that is defined in the <stdlib.h> library.
Note: The rand() function by default uses the value 1 as the seed to generate random numbers which leads to the generation of the same sequence of random numbers. To prevent this, we can use srand() function to specify a new seed for rand() function.
Examples of rand() in C
Example 1: Illustration of rand() function
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int value = rand ();
printf ( "The Random Value is: %d" , value);
return 0;
}
|
Output
The Random Value is: 1804289383
Time Complexity: O(1)
Space Complexity: O(1)
Example 2: Generate 10 Random Numbers
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
for (; i < 10; i++) {
int value = rand ();
printf ( "%d " , value);
}
return 0;
}
|
Output
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421
But, if we want to generate some random numbers in the range of 0 to N then, we need to modify by printing the modulo of (N+1) of the numbers that are generated by the rand() function.
Example: Generate Random Numbers Smaller than N
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N = 1000;
for ( int i = 0; i < 10; i++) {
int value = rand () % (N + 1);
printf ( "%d " , value);
}
return 0;
}
|
Output
897 802 765 992 1 521 220 380 729 969
In this way, we can easily generate the random number from 0 to N.
Also, if we want a random number that will exist between a lower_bound and upper_bound, we can do this by using simple mathematics on the random number that is generated by rand() function.
Example: Generate Random Numbers Within a Range
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int upper_bound = 1000;
int lower_bound = 100;
for ( int i = 0; i < 10; i++) {
int value = rand () % (upper_bound - lower_bound + 1)
+ lower_bound;
printf ( "%d " , value);
}
return 0;
}
|
Output
943 897 704 678 132 783 902 760 689 765
Share your thoughts in the comments
Please Login to comment...