Random Number Generator in C++

The ability for a program to generate random numbers is essential in many situations. Nearly every game has to do with random generation, such as a game that involves dice or any kind of card game. Random numbers are essential because how boring would it be if a game was always the same and predictable? Here is program coded in C++ that will generate a random number from 0 to 5.

//Full Working Program
//Program to generate a number between 0 and 5
#include <iostream>
#include <stdlib.h>//required to use 'rand()'
#include <time.h>//required to use 'srand(time(NULL))'

using namespace std;

int main()
{
srand(time(NULL));//required for "randomness"

 int r;
 r=rand()%6;//generate a number between 0 and 5
 cout<<r<<endl;

return 0;
}

-HOW IT WORKS-

The algorithm to generate random numbers is actually very simple thanks to the 'rand()' function. However, before we can use this function we must declare the standard library header file.

#include <stdlib.h>

If we were to use try to use the 'rand()' function without declaring the pre processor directive '' then the compiler will complain.

#include <time.h>

The time header file is required to use 'srand(time(NULL))' this is because this function uses the clock on your computer to determine the "randomness" of your numbers. Every second the program will spit out a random number, if you were to not use the 'srand(time(NULL))' then the program will spit out the same number every time, try it for yourself!

r=rand()%6;

Here the variable 'r' will equal a number from 0 to 5 if I were to put 8 instead of 6 then 'r' would equal a number from 0 to 7. This is thanks to 'rand()' which randomly generates a number and works with the modulus operator '%' spits out the remainder. What the modulus operator does is compute division and returns the remainder. For example if you had 10%4 the answer would be 2. This is because 4 goes into 10 twice with a remainder of 2.

So why will 'r' equal a number from 0 to 5? Remember 'rand()' computes a random number and the modulus returns a remainder so no matter what the number is as long as we divide it by 6 it can only have a remainder from 0 to 5, so say in one case that 'rand()' computes 13 that means 'r' would equal 13%6 and would thus equal 1. If 'rand()' computed 14 then 14%6 equals 2, 15%6 equals 3, 16%6 equals 4, 17%6 equals 5, 18%6 equals 0 (because there is no remainder), 19%6 equals 1, and now we are back to 1.

rand() % n//algorithm to generate a number from 0 to n-1

If we didn't want to generate a random number from 0 to 5, but 1 to 6 like rolling a piece of die. All we have to do is add 1 like this.

rand() % n+1//algorithm to generate a number from 1 to n