×

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

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.