Random number within a range

Generating a random number in C++ is easy, but for generating one within a range you must use a little trick.

First, let’s see the script and then we shall analyze it.

// Generating a random number within a range

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
    srand(GetTickCount());
    int i = rand()%10;
    cout << i;
    return 0;
}
#include <windows.h>

-we must include ‘windows.h’ because we use GetTickCount().

srand(GetTickCount());

-it retrieves the number of milliseconds elapsed since the system start. This is the trick for getting a random number. If we don’t use this function, we will get a random number, but the same number all the time. This is the way a computer creates a random number… the time.

int i = rand()%11; – this is the trick we use to get the number within a given range. We use the modulus operator to get the rest of the division of the number by eleven (because if we used %10 and the random number would be 10, 10%10 = 0).

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top