Generating random numbers is crucial for many applications, including games, simulations, and cryptography. In C, random numbers are generated using functions from the <stdlib.h> library.
rand() FunctionThe rand() function returns a pseudo-random integer between 0 and a large constant called RAND_MAX (typically 32767).
#include <stdio.h> #include <stdlib.h>int main() { // Generate and print a random number int randomNum = rand(); printf("Random Number: %d\n", randomNum); return 0; }
If you run the code above multiple times, you might notice it generates the exact same sequence of numbers every time the program runs! This is because rand() is pseudo-random and uses a default "seed" value of 1.
srand()To get truly different random numbers each time you run the program, you must provide a new seed to the random number generator using the srand() function.
The most common way to do this is to use the current time as the seed, using time(NULL) from the <time.h> library.
#include <stdio.h> #include <stdlib.h> #include <time.h>int main() { // Seed the random number generator with current time srand(time(NULL)); // Now rand() will produce different results each run printf("Random 1: %d\n", rand()); printf("Random 2: %d\n", rand()); return 0; }
Usually, you don't want a number between 0 and 32767. You want a number in a specific range, like rolling a dice (1 to 6). You can achieve this using the modulo operator %.
Formula: rand() % (max_number + 1 - minimum_number) + minimum_number
#include <stdio.h> #include <stdlib.h> #include <time.h>int main() { srand(time(NULL)); // Generate a random number between 1 and 6 int diceRoll = (rand() % 6) + 1; printf("You rolled a: %d\n", diceRoll); return 0; }
Why do we use the srand() function before calling rand()?