Random number generation in C/C++
For example rand() % 10 returns any value from 0 to 9. But rand() alone is not the solution of random number as it always returns a same value no matter how many times you execute a program. This is not what we want. We want to generate different numbers in each execution. This can be done by calling another function srand(). We must synchronize rand() with time to produce random numbers. The following example generates a random number with range [0, 9].
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main(){ int n; srand(time(NULL)); n = rand() % 10; cout<<"The random number is "<<n; return 0; }