What makes the throw of dice special is the fact that you can’t always guess which number will come up. This property is known as randomness, which is needed in certain types of programs (ex. Games).
In this article, we are going to discuss how random numbers are generated and used in C++ with the help of a simple example.The program illustrates generation and use of random numbers in C++:
//C++ Program to generate RANDOM NUMBERS
//function is isolated so it may be easily
//incorporated in other programs
//NOTE:stdlib.h header file is required
//for using this funtion elsewhere
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
//FUNCTION PROTOTYPE
int random(int HighestNumber,int LowestNumber);
void main(void)
{
char ch = '';
puts("Random Number Generator: ");
while(ch!='q' && ch!='Q')
//loop until q or Q is pressed
{
puts("Press any key to throw dice...");
ch=getch();
//%d tells the compiler that the value after
//the comma is of integer type (value returned
//by the function)
printf("%d",random(6,1));
puts("\nPress Q to QUIT");
}
}
//USER-DEFINED FUNCTION
//it takes two integer arguments and returns a
//random number in between the two.
int random(int HighestNumber,int LowestNumber)
{
//rand() is a standard library function
//which generates random numbers, these are
//operated to get the numbers within range
//stdlib.h header file is necessary for its
//operation
int i=((rand()%(HighestNumber-LowestNumber+1))+LowestNumber);
return i;
}
Hope this article helps!