Random Number Generator in C
In C, you can use the rand() function from the stdlib.h library to generate a random number. To get a random number within a specific range, you might need to perform some additional operations. Here's an example to generate a random integer between 1 and 10, inclusive:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Initialize random seed
srand(time(NULL));
// Generate a random number between 1 and 10
int randomNumber = rand() % 10 + 1;
// Print the random number
printf("Random Number: %d
", randomNumber);
return 0;
}
In this code:
- srand(time(NULL)) initializes the random number generator with the current time as the seed. This line is usually called once at the beginning of the program to ensure that rand() produces different sequences of random numbers each time the program runs.
- rand() % 10 generates a random number between 0 and 9.
- Adding 1 (+ 1) shifts the range to 1–10, making the result fall between 1 and 10, inclusive.
- printf() is used to print the random number to the console.