In C, you can generate random numbers using two key functions:
Method 1: Using rand()
The rand() function returns a pseudo-random integer. You can scale or mod it to fit a desired range.
#include <stdio.h>
#include <stdlib.h>
int main() {
int random_number = rand();
printf("Random Number: %d\n", random_number);
return 0;
}Since rand() produces a pseudo-random number, the same sequence will repeat
on each execution unless you change the seed.
Method 2: Using srand()
The srand() function seeds the random number generator, typically with the current time, to ensure the random sequence varies on each program run.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
int random_number = rand();
printf("Random Number: %d\n", random_number);
return 0;
}By using srand() with time(0), you get a fresh sequence of random numbers
every time you run the program.
Conclusion
Using srand() and rand() together allows you to generate random numbers effectively in C.
rand()generates random numbers.srand()seeds the random number generator for varied output.
Happy coding!
Written by
Shyam Verma
At
Oct 1, 2024
Last updated on
Read time
2 min
Tags