Random numbers are numbers that are selected randomly. Selecting a random number can provide security, uniqueness, etc. C programming language provides the rand() function which returns pseudo-random numbers.
rand() Function Syntax
The rand() function syntax is like below.
rand()
As we can see there is no parameter. The random number is returned as an integer. Before using the rand() method it should be seeded with the srand() function. The srand() function requires some random value. The random value can be the current time which can be returned with the time(0) function like below.
srand(time(0))
Generate Random Number
A random number is generated first seeding the rand() function with the srand() function. Then simply run the rand() function and storing the returned random number. The upper limit of the random numbers is set with the RAND_MAX macro. In most of the systems, the RAND_MAX or the upper limit of the random number is 2147483647.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generate Random Number
int main()
{
int random_number;
// Use current time as
// seed for random generator
srand(time(0));
random_number = rand();
printf("%d",random_number);
return 0;
}
Set Limit For Random Number with Modulo
The upper limit or maximum value of the returned number can be set with modulo operator. Actually the returned value is not limited but by using the modulo operation and operator the upper limit can be specified like below. In the following example the limit is set as 100.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generate Random Number
int main()
{
int random_number;
int limit = 100;
// Use current time as
// seed for random generator
srand(time(0));
random_number = rand()%limit;
printf("%d",random_number);
return 0;
}