C++ - Program - Random Numbers

#include <iostream>
#include <random>
int main() {
    // Create a random number generator engine
    std::random_device rd;
    std::mt19937 mt(rd());
    // Generate random numbers between 1 and 100
    std::uniform_int_distribution<int> dist(1, 100);
    // Generate and print 5 random numbers
    for (int i = 0; i < 5; i++) {
        int randomNumber = dist(mt);
        std::cout << "Random Number: " << randomNumber << std::endl;
    }
    return 0;
}

In this program, we use the <random> library to generate random numbers. Here's a breakdown of the code:

The std::random_device class is used to obtain a random seed for the random number generator engine.

The std::mt19937 class is a random number generator engine based on the Mersenne Twister algorithm.

We create an instance of std::random_device named rd, and then use it to initialize the Mersenne Twister engine mt.

Next, we define a range for the random numbers using the std::uniform_int_distribution class. In this example, we set the range to be between 1 and 100.

Inside the for loop, we generate random numbers using dist(mt). This generates a random number using the Mersenne Twister engine mt and the specified distribution dist.

The random number is then printed to the console using std::cout.

The loop repeats five times, generating and printing five random numbers.