Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/numbers/cpp$ _

Generate Random Numbers in C++

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: C++

What: Generate random numbers in C++ using the modern <code>&lt;random&gt;</code> library with <code>uniform_int_distribution</code> and <code>mt19937</code> for high-quality random number generation.

Try it: Use our interactive Numbers generator or integrate this code into your C++ application.

Generate random numbers in C++ using the modern <random> library with uniform_int_distribution and mt19937 for high-quality random number generation. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , Ruby and Go or use our interactive web generator.

C++ Code Example

#include <iostream>
#include <random>
#include <vector>

int main() {
    // Initialize random number generator
    std::random_device rd;  // Seed
    std::mt19937 gen(rd()); // Mersenne Twister engine
    std::uniform_int_distribution<> distrib(1, 100);

    // Generate a single random number between 1 and 100
    int randomNumber = distrib(gen);
    std::cout << randomNumber << std::endl;  // Example output: 42

    // Generate multiple random numbers
    std::vector<int> numbers;
    for (int i = 0; i < 10; ++i) {
        numbers.push_back(distrib(gen));
    }

    std::cout << "[";
    for (size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i];
        if (i < numbers.size() - 1) std::cout << ", ";
    }
    std::cout << "]" << std::endl;
    // Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]

    // Random double between 0 and 100
    std::uniform_real_distribution<> realDistrib(0.0, 100.0);
    double randomDouble = realDistrib(gen);
    std::cout << std::fixed << std::setprecision(2) << randomDouble << std::endl;
    // Example: 42.17

    return 0;
}

[EXPLANATION]

Modern C++ (C++11+) provides the <random> library with uniform_int_distribution for uniform random integers and mt19937 (Mersenne Twister) for high-quality pseudo-random number generation. random_device provides non-deterministic seeds.

Expected Output

42
[23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
42.17

Common Use Cases

  • Game development and game engines (Unreal, Unity plugins)
  • Scientific computing and simulations
  • Cryptographic applications with proper seeding
  • Systems programming requiring random data
  • High-performance numerical computing
  • Embedded systems and IoT devices

Important Notes

  • Avoid old rand() function - use <random> instead
  • mt19937 is Mersenne Twister - high quality PRNG
  • random_device may be deterministic on some platforms
  • Requires C++11 or later (-std=c++11 flag)

Try Our Interactive Generator

Don't want to write code? Use our free web-based Numbers generator with instant results.

TRY NUMBERS GENERATOR →