C Program to Generate Random Number with Output Example
rand() to generate a random number in C and srand(time(NULL)) to seed the generator for different results each run, like this: srand(time(NULL)); int num = rand();.Examples
How to Think About It
srand() with the current time so the numbers change each time you run the program. Then you call rand() to get a random number. This number is usually large, so you can use the modulus operator % to limit it to a smaller range if needed.Algorithm
Code
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int random_number = rand(); printf("Random number: %d\n", random_number); return 0; }
Dry Run
Let's trace the program generating a random number step-by-step.
Seed the generator
Call srand(time(NULL)) with current time, e.g., 1680000000, to set the seed.
Generate random number
Call rand(), which uses the seed to produce a pseudo-random number, e.g., 1804289383.
Print the number
Print the generated number: 1804289383.
| Step | Action | Value |
|---|---|---|
| 1 | Seed with time | 1680000000 |
| 2 | Generate rand() | 1804289383 |
| 3 | Print output | Random number: 1804289383 |
Why This Works
Step 1: Seeding with srand()
Using srand(time(NULL)) sets a different starting point for the random number generator each time the program runs, so numbers vary.
Step 2: Generating with rand()
rand() produces a pseudo-random integer based on the seed, simulating randomness.
Step 3: Printing the result
The program prints the generated number so you can see the random value.
Alternative Approaches
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int min = 1, max = 100; int random_number = rand() % (max - min + 1) + min; printf("Random number between %d and %d: %d\n", min, max, random_number); return 0; }
#include <stdio.h> #include <stdlib.h> int main() { unsigned int random_number = arc4random(); printf("Random number: %u\n", random_number); return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
Generating a random number with rand() takes constant time because it performs a fixed number of operations.
Space Complexity
The program uses a fixed amount of memory for variables and does not allocate extra space.
Which Approach is Fastest?
Using rand() is fast and simple; alternatives like arc4random() may be slower but offer better randomness.
| Approach | Time | Space | Best For |
|---|---|---|---|
| rand() with srand() | O(1) | O(1) | Simple random numbers, portable |
| rand() with modulus for range | O(1) | O(1) | Random numbers in a specific range |
| arc4random() | O(1) | O(1) | Better randomness on supported systems |
srand(time(NULL)) to get different numbers each run.srand() causes rand() to produce the same sequence every time.