C++ Program to Seed Random Number Generator
The below example demonstrates how we can seed random number generator in C++.
// C++ Program to Seed Random
// Number Generator
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
// declare seed value as unsigned int
unsigned int seed;
// Ask user input for seed value
cout << "Enter the Seed Value: ";
cin >> seed;
// Seed the random number generator with user-provided
// value
srand(seed);
// Generate and print a sequence of pseudo-random
// numbers
for (int i = 0; i < 5; ++i) {
long long randomNum = rand();
cout << "Random Number " << i + 1 << " "
<< randomNum << endl;
}
return 0;
}
Output
Enter the Seed Value: 4
Random Number 1 1968078301
Random Number 2 287724083
Random Number 3 410622274
Random Number 4 558519326
Random Number 5 460165363
Time Complexity: O(1)
Auxilary Space: O(1)
How to Seed a Random Number Generator in C++?
In C++, seeding a random number generator is important for generating different sequences of random numbers on each program run. This process consists of initializing the generator with a starting value, known as a seed. This ensures the randomness and unpredictability required for various applications such as simulations, games, and statistical sampling. In this article, we will learn how to seed a random number generator in C++.
Example:
Input:
Enter the Seed Value: 4
Output:
Random Number 1 1968078301
Random Number 2 287724083
Random Number 3 410622274
Random Number 4 558519326
Random Number 5 460165363