#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
// Seed the random number generator
srand(static_cast<unsigned int>(time(nullptr)));
// Generate a random number between 1 and 10
int randomNumber = rand() % 10 + 1;
// Output the random number
std::cout << "Random number: " << randomNumber << std::endl;
return 0;
}
#include <iostream>
: Includes the input/output stream library.#include <cstdlib>
: Includes the C standard library for functions like rand()
and srand()
.#include <ctime>
: Includes the C time library to use functions related to time.
int main() { ... }
: The main function, the entry point of the program.
srand(static_cast<unsigned int>(time(nullptr)));
: Seeds the random number generator by converting the current time (in seconds since Jan 1, 1970) to an unsigned integer and using it as the seed value for srand()
. This step ensures a different seed each time the program runs.
int randomNumber = rand() % 10 + 1;
: Generates a random number between 0 and 9 using rand()
and % 10
, then adds 1 to make the range 1 to 10.
std::cout << "Random number: " << randomNumber << std::endl;
: Outputs the generated random number to the console.
return 0;
: Indicates successful execution and termination of the program.