Random Number Generation in C++

3 Min Read

Generation of random numbers is a popular problem of programming in C, C++, etc. It is important in coding many software and games for carrying random actions such as randomly withdrawing the questions in quiz, in playing dice, etc. This Random Number Generation in C++ is a tutorial post to demonstrate the application of C++ programming language to generate random numbers.

In this post, the source code to generate random number in C++ is presented along with its algorithm and output screen. The algorithm presented here can be used to write a program for generating random number in any high level language.

Algorithm:

  • Start
  • Declare random variable, (say r)
  • Call the strand function with time (NULL)
  • Call random function
  • Assign random number with random function return
  • Print the random number generated as console output
  • Stop

Source Code for Random Number Generation in C++:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;
int main()
{
   int r; // declaration of random variable
   srand(time(NULL)); // calling of strad function with time as argument
   r = rand() % 100; // random variable generation
   cout<<"The generated random number is "<<r; // printing output
   return 0;
}

The source code of the program involves three header files: iostream, cstdlib and ctime. The iostream defines the general input/output function in C++ programming. The rand() is included in cstblib library of C++ header files and the ctime is declared to control the time() function and strand() function.

The library function rand() plays vital role in generation of random numbers. When this function is called, it returns an integer from 0(0x0000) to 32767 (0x7FFFF). In order to control the digit of random number, the remainder of return of rand() function, when divided by certain number, is selected as random number.

When the given C++ source code for Random Number Generation is executed, it generates the random numbers of two digits. It due to the fact that the random number ‘r’ has been assigned to rand() % 100. If it would be assigned to rand() % 10, the output will be of single digit.  There will be different outputs for various execution of program as shown below.

Sample Output 1
Sample Output 2

I hope the given program source code in C++ for Random Number Generation is short and simple to understand. You can find other C++ tutorials here. If you have any queries regarding the tutorial, algorithm or source code, mention them in the comments.

Share This Article
Leave a comment

Leave a Reply

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

English
Exit mobile version