Skip to content
Related Articles

Related Articles

Improve Article

C++ program to generate random number

  • Difficulty Level : Hard
  • Last Updated : 03 Jan, 2018
Geek Week

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)

// 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;
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :