Random number generation in C/C++

Many programs need a random number to complete their certain goal. For example, a quiz program needs random number to randomize the question number to be asked first. Likewise, a dice game needs a random number to select the face when it is thrown. So there are many situations where the need of random number has no alternatives. Almost all programming languages provide the way to generate random numbers. In the same way C/C++ also provides some functions that generate random numbers. stdlib.h in C and cstdlib in C++ provides a function rand() to generate a random number. This function, when called, returns a integer from 0(0x0000) to 32767 (0x7FFFF).

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;

}
SHARE Random number generation in C/C++

You may also like...

Leave a Reply

Your email address will not be published.

Share