C++ program to generate random number

The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function.

Prerequisite : random header in C++ | Set 1(Generators)

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to generate random number
#include <bits/stdc++.h>
using namespace std;
  
// Function with return random number from 1 to
// given limit
int randomNoGenerator(int limit)
{
    // uniformly-distributed integer random number
    // generator that produces non-deterministic
    // random numbers.
    random_device rd;
  
    // A Mersenne Twister pseudo-random generator
    // of 32-bit numbers with a state size of
    // 19937 bits.
    mt19937 gen(rd());
  
    // Uniform distribution
    uniform_int_distribution<> dis(1, limit);
    return dis(gen);
}
  
// Driver Code
int main()
{
    int limit = 100;
    cout << randomNoGenerator(limit) << endl;
    return 0;
}

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.