Generating Random Numbers in C++

To generate random numbers c++ provides a function rand(), which is present in the header file
#include <cstdlib>

rand() function returns an integer in the range 0 to RAND_MAX(2147483647). If you want the rand() function to generate random numbers only in the range between 0 to 10. you can write

rand()%10 + 1

The problem with using only rand() function is that you will start observing the same sequence of numbers after execution. If you want to get a different sequence of numbers ,you have to perform a operation called seeding .

The function which performs seed is srand() and takes integer as an argument.

Keep in mind that you should call the srand() function only once. 

A commonly used technique is to seed the random number generator using clock. The time() function will return the number of seconds elapsed since Jan1, 1970. You can pass this as an argument to srand().



Sample Code:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
   int number;
   srand(time(NULL));
   for(int i = 0; i < 10; i++)
   {
       number = rand()%10 + 1;
       cout << number << " " << endl;
   }
   cout << endl;
    return 0;
}


References:
http://www.math.uaa.alaska.edu/~afkjm/csce211/handouts/RandomFunctions.pdf

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto