0
0
CppProgramBeginner · 2 min read

C++ Program to Generate Random Number

Use the C++ <random> library to generate random numbers by creating a std::mt19937 engine and a distribution like std::uniform_int_distribution, then call the distribution with the engine to get a random number.
📋

Examples

InputNo input needed
OutputRandom number between 1 and 100: 42
InputNo input needed
OutputRandom number between 1 and 100: 7
InputNo input needed
OutputRandom number between 1 and 100: 99
🧠

How to Think About It

To generate a random number in C++, first create a random engine that produces pseudo-random numbers. Then, define a range using a distribution, such as uniform integer distribution, to limit the random numbers to a specific range. Finally, generate the number by combining the engine and distribution.
📐

Algorithm

1
Include the <random> and <iostream> headers.
2
Create a random device to seed the random engine.
3
Initialize a Mersenne Twister engine with the seed.
4
Define a uniform integer distribution with the desired range.
5
Generate a random number by calling the distribution with the engine.
6
Print the generated random number.
💻

Code

cpp
#include <iostream>
#include <random>

int main() {
    std::random_device rd;  // Seed generator
    std::mt19937 gen(rd()); // Random engine
    std::uniform_int_distribution<> dist(1, 100); // Range 1 to 100

    int random_number = dist(gen); // Generate number
    std::cout << "Random number between 1 and 100: " << random_number << std::endl;
    return 0;
}
Output
Random number between 1 and 100: 57
🔍

Dry Run

Let's trace generating a random number between 1 and 100 through the code.

1

Seed creation

random_device rd creates a seed value, e.g., 123456789

2

Engine initialization

mt19937 gen is initialized with seed 123456789

3

Distribution setup

uniform_int_distribution dist is set for range 1 to 100

4

Generate random number

dist(gen) produces a number, e.g., 57

5

Output

Prints: Random number between 1 and 100: 57

StepActionValue
1Seed from random_device123456789
2Initialize mt19937 engineSeed=123456789
3Set distribution range1 to 100
4Generate random number57
5Print outputRandom number between 1 and 100: 57
💡

Why This Works

Step 1: Seed the engine

The std::random_device provides a random seed to initialize the engine, ensuring different results each run.

Step 2: Use Mersenne Twister engine

The std::mt19937 engine generates high-quality pseudo-random numbers efficiently.

Step 3: Define distribution range

The std::uniform_int_distribution limits the random numbers to the desired range, here 1 to 100.

Step 4: Generate and print

Calling the distribution with the engine produces a random number, which is then printed.

🔄

Alternative Approaches

Using <cstdlib> and rand()
cpp
#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    std::srand(std::time(nullptr)); // Seed
    int random_number = std::rand() % 100 + 1; // 1 to 100
    std::cout << "Random number between 1 and 100: " << random_number << std::endl;
    return 0;
}
This is simpler but less random and not recommended for modern C++.
Using <random> with uniform_real_distribution
cpp
#include <iostream>
#include <random>

int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dist(0.0, 1.0);
    double random_number = dist(gen);
    std::cout << "Random real number between 0 and 1: " << random_number << std::endl;
    return 0;
}
Generates a floating-point random number instead of integer.

Complexity: O(1) time, O(1) space

Time Complexity

Generating a random number is a constant time operation because it involves a fixed number of steps without loops.

Space Complexity

Only a few variables for the engine and distribution are used, so space is constant.

Which Approach is Fastest?

Using rand() is slightly faster but less random; <random> provides better randomness with negligible performance cost.

ApproachTimeSpaceBest For
with mt19937O(1)O(1)High-quality random numbers
rand() with srand()O(1)O(1)Simple, legacy code
uniform_real_distributionO(1)O(1)Random floating-point numbers
💡
Always seed your random engine with std::random_device to get different random numbers each run.
⚠️
Beginners often forget to seed the random engine, causing the same number to appear every time.