In C, we can use rand() function to generate a random number. It is defined in stdlib.h header file and it generates a random number between 0 and RAND_MAX. In my computer, RAND_MAX returns 532767.
Some posts on the Internet share a way to generate a random number like this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand(time(NULL));
printf("%d", rand());
}
To generate a random number in a given range from a lower number to an upper number, some people make a function, like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
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);
}
}
int main(){
int lower = 5, upper = 7, count = 1;
srand(time(0));
printRandoms(lower, upper, count);
}
In my opinion, using rand() is not a secure way of generating random numbers if you are developing a real-world application. To generate a secure random number, here is my solution:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int RAND(int a,int b){
float d=RAND_MAX/(b-a+1);
return a+round(rand()/d);
}
int main(){
for(int i=1;i<=10;i++){
printf("%5d",RAND(2,5));
}
printf("%d",RAND_MAX);
}
Instead of using srand(time(0)), I create a function to generate a random number in the [a;b] range. I have split RAND_MAX into $d=b-a+1$ chunks. Then round the division rand()/d to integer, this results in a range from $0$ to $b-1$. So I added $a$ to get the desired result.