C++ How To Generate Random Numbers

Welcome to The Coding College! In this tutorial, we’ll explore how to generate random numbers in C++. Random numbers are widely used in simulations, games, cryptography, and more. We’ll go through different methods to create random numbers using modern C++ features.

Random Numbers in C++

Random number generation in C++ is achieved using the following:

  1. C Standard Library (rand() and srand())
  2. C++11 Random Library (<random>)

Including Required Headers

#include <iostream>
#include <cstdlib>   // For rand() and srand()
#include <ctime>     // For time()
#include <random>    // For C++11 random library
using namespace std;

Method 1: Using rand()

The rand() function generates pseudo-random numbers.

Example: Basic Random Numbers

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    for (int i = 0; i < 5; i++) {
        cout << "Random number: " << rand() << endl;
    }
    return 0;
}

Output:

Random number: 1804289383  
Random number: 846930886  
Random number: 1681692777  
Random number: 1714636915  
Random number: 1957747793  

Explanation:

  • The numbers appear random but are deterministic because rand() generates numbers based on a fixed seed.

Seeding with srand()

Use srand() with time(0) to make the numbers more random by seeding with the current time.

Example: Seeded Random Numbers

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));  // Seed with current time

    for (int i = 0; i < 5; i++) {
        cout << "Random number: " << rand() << endl;
    }
    return 0;
}

Output (varies):

Random number: 13579246  
Random number: 98765432  
Random number: 12345678  
Random number: 24681357  
Random number: 86420987  

Generating Numbers in a Range

To limit the range of random numbers, use the modulo operator (%).

Example: Random Numbers in a Specific Range

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));  // Seed with current time

    for (int i = 0; i < 5; i++) {
        int randomNum = rand() % 100 + 1;  // Random number between 1 and 100
        cout << "Random number: " << randomNum << endl;
    }
    return 0;
}

Output (varies):

Random number: 42  
Random number: 98  
Random number: 56  
Random number: 12  
Random number: 73  

Method 2: Using <random> (C++11 and Beyond)

Modern C++ provides a better way to generate random numbers using the <random> header, offering more control and better randomness.

Example: Using std::uniform_int_distribution

#include <iostream>
#include <random>
using namespace std;

int main() {
    random_device rd;                    // Seed source
    mt19937 gen(rd());                   // Mersenne Twister engine
    uniform_int_distribution<> dist(1, 100);  // Range [1, 100]

    for (int i = 0; i < 5; i++) {
        cout << "Random number: " << dist(gen) << endl;
    }

    return 0;
}

Output (varies):

Random number: 47  
Random number: 3  
Random number: 89  
Random number: 21  
Random number: 66  

Generating Floating-Point Numbers

Use std::uniform_real_distribution to generate random floating-point numbers.

Example: Random Floating-Point Numbers

#include <iostream>
#include <random>
using namespace std;

int main() {
    random_device rd;                    // Seed source
    mt19937 gen(rd());                   // Mersenne Twister engine
    uniform_real_distribution<> dist(0.0, 1.0);  // Range [0.0, 1.0]

    for (int i = 0; i < 5; i++) {
        cout << "Random number: " << dist(gen) << endl;
    }

    return 0;
}

Output (varies):

Random number: 0.254763  
Random number: 0.869234  
Random number: 0.456123  
Random number: 0.123456  
Random number: 0.789123  

Comparing rand() and <random>

Featurerand()<random> (C++11+)
ControlLimitedExtensive
Range SpecificationManual (modulo)Built-in
SeedingManual (srand())Automatic or customizable
Randomness QualityLowerHigher
RecommendedLegacy codeModern applications

Real-World Example: Rolling a Dice

Example: Simulate Dice Rolls

#include <iostream>
#include <random>
using namespace std;

int main() {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dice(1, 6);

    cout << "Rolling the dice..." << endl;
    for (int i = 0; i < 5; i++) {
        cout << "You rolled: " << dice(gen) << endl;
    }

    return 0;
}

Output (varies):

Rolling the dice...  
You rolled: 3  
You rolled: 6  
You rolled: 2  
You rolled: 5  
You rolled: 1  

Summary

  • Use rand() for basic random numbers and <random> for more control and higher quality randomness.
  • Always seed your random number generator for varied outputs.
  • Use <random> for modern C++ applications to access advanced randomization features.

Learn More at The Coding College

Visit The Coding College for more tutorials on C++, programming techniques, and advanced concepts.

Leave a Comment