×

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T

There are two tools available in C++ to generate random numbers. We shall first examine those tasks and comprehend their requirements. Later, to implement the functionality, we will use them in our code. So, let's start with the library and functions it is related to.

How is a random number generated?

C++ offers the facilities needed to generate random numbers. We know that the C++ header file contains most of the built-in functions. Stdlib.h is one such header file. It is a standard library with numerous built-in functions, including EXIT FAILURE, EXIT SUCCESS, RAND MAX, NULL, and others. These functions make it simple to find the needed solution. To get out, we don't need to compose a lengthy argument. Instead, we may use a built-in function that we need by calling it.

Let's examine the main components of those functions.

  • Randomise ()

Every time you execute the software, a random number is generated by this function. Every time the code is completed, a different result will be produced. We rely more on this function because of this particular output. For instance, when you run the code for the first time, the outcome will be 75, 23, 56, 24, 5, 21, 76, 32, 20 and 37. The next time, the output will be 5, 64, 51, 78, 94, 53, 41, 19, 96, and 52. In the next section, we'll write some code to examine the output with and without this function.

  • Rand ()

We will use this function to produce the range of values from 0 to RAND MAX-1. RAND MAX denotes the most expansive feasible number field in this context. Let's imagine we need to create random numbers between 0 and 99; in such case, RAND MAX will have a value of 100. The value of RAND MAX is selected following the application requirements we want to construct. For instance, the RAND MAX for a dice game will be 6. RAND MAX will be 52, for example, if it's a card game.

Just keep in mind that the standard library's stdlib.h contains declarations for both functions. Therefore, remember to add this header file to your code. Let's now examine how to create a straightforward random number generator program.

Steps

Let's write the software piece by piece to understand better how it operates.

  • The two header files required for the application must be included as the first step. Stdlib.h is the second and most significant header file. Therefore, start the code with both.
#include <iostream>
#include <stdlib.h>
using namespace std;
  • Writing the primary function to execute the code is the next step after including the header files. To specify the primary purpose in the next section.
int main( )
{
}
  • Declare a number to hold, and then print the random number's value. The data type can have any name and be of the int data type.
int  number;
  •  Declare the type of the index, I as being int. The maximum increment value will be set in the
circle.
int I;
  • To print the values of the randomly generated integer, we will now create for a loop. We're printing ten numerals to make things easier. Therefore, there can be a maximum of 10 increments.
for(i = 1; i <= 10; i++)
{
}
  • We will write the rand function within for loop. The code shown below instructs us to divide any produced random integer by 100 and then take the remaining. This indicates that the range of the printed integers will be 0 to 99. Higher degrees will result in a different modulo number. In other words, we may substitute 150, 200, 100, etc., for 100.
number = rand() % 100;
  • The generated number will be printed using cout in the final step.
cout << number  << "\t";
  • The code's output appears as follows. Please be aware that the random number generator may produce different results.
Random Number Generator in C++
  • To prevent this, we must use the rand () function, which refers to the time at that instance and has new numbers each time the program is executed.

Let's examine the entire code using the srand function:

Example 1:

#include <iostream>
#include <stdlib.h>
using namespace std;
int main( )
{
int  number;
int I;
srand(time(0));
for(i = 1; i <= 10; i++)
{
number = rand() % 100;
cout << number  << "\t";
}
}

The code's two execution results are:

Initial Application:

Random Number Generator in C++

Additional Execution:

Random Number Generator in C++
  • This code will create five random numbers from a range of 1000. Change the number's value to observe the output produced each time. Examine the variations between using unsigned and without using.

Example 2:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int I, number;
time_t time;
number = 5;
srand((unsigned) time(&nTime));
printf("Random numbers are: \n");
for( i = 0 ; i < number ; i++ )
{
printf("%d\n", rand() % 1000);
}
return(0);
}

Output:

Initial iteration

Random Number Generator in C++

Second iteration

Random Number Generator in C++

Related Topics

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.