1. Introduction
In programming, random numbers are used for a variety of purposes and are especially widely applied in the C language. Random numbers are an important concept used in many scenarios, such as creating game scenarios, performing random sampling, and shuffling data. In this article, we will explain in detail how to generate random numbers in C and provide examples of how they can be used in practice. By understanding random number generation in C, you can broaden your ability to apply it effectively.
2. What Is a Random Number?
The Concept of Random and Pseudorandom Numbers
A random number refers to a value that is unpredictable and typically generated arbitrarily within a given range. However, random numbers generated by a computer are actually called “pseudorandom numbers” because they are created according to a set of rules, making them not truly random. Since pseudorandom numbers are generated by an algorithm, using the same seed value (initial value) will produce the same sequence of numbers.
3. How to Generate Random Numbers in C
The C standard library provides functions for generating random numbers. Here, we will focus on the commonly used rand()
function, the RAND_MAX
constant, and the srand()
function for setting the seed value.
Basics of the rand() Function
The rand()
function is the basic function in C for generating random numbers. It returns a random integer between 0 and RAND_MAX
. The value of RAND_MAX
is a constant defined in the library and depends on the system or environment, but it is typically 32767.
#include <stdio.h>
#include <stdlib.h>
int main() {
int random_number = rand();
printf("Random number: %d\n", random_number);
return 0;
}
In the above code, the rand()
function generates a random integer between 0 and 32767 and displays it.
Setting the Seed Value with srand()
The rand()
function generates numbers based on a seed value, so by default it produces the same sequence of numbers each time the program runs. To prevent this, you can set a seed value using the srand()
function, enabling the generation of different sequences. A common method is to set the current time as the seed value.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned int) time(NULL)); // Initialize seed with current time
int random_number = rand();
printf("Random number: %d\n", random_number);
return 0;
}
In this example, time(NULL)
retrieves the current time and sets it as the seed. This ensures that each program run generates a different sequence of random numbers.
Generating Random Numbers Within a Specific Range
To generate random numbers within a specific range (e.g., from 1 to 10), use the rand()
function as follows:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned int) time(NULL));
int min = 1;
int max = 10;
int random_number = min + rand() % (max - min + 1);
printf("Random number between %d and %d: %d\n", min, max, random_number);
return 0;
}
This code generates a random number between 1 and 10. The expression rand() % (max - min + 1)
ensures the result falls within the specified range.

4. Practical Applications of Random Numbers
Here are some examples of practical uses for random numbers.
Dice Simulation
You can simulate rolling a die by generating a random number between 1 and 6.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned int) time(NULL));
int dice_roll = 1 + rand() % 6;
printf("Dice roll: %d\n", dice_roll);
return 0;
}
This program randomly outputs a number between 1 and 6, simulating a die roll.
Shuffling an Array
You can shuffle the elements of an array by randomly swapping them.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int *array, int size) {
for (int i = 0; i < size; i++) {
int j = rand() % size;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int main() {
srand((unsigned int) time(NULL));
int array[] = {1, 2, 3, 4, 5, 6};
int size = sizeof(array) / sizeof(array[0]);
shuffle(array, size);
printf("Shuffled array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
This code shuffles the elements of an array by randomly swapping them.
Using Random Numbers in Game Development
In game development, random numbers are used for tasks such as determining enemy spawn locations or generating items. By using random numbers, you can add unpredictability to games, creating a more realistic experience for players.
5. Points to Note When Generating Random Numbers
Limitations of the rand() Function
While rand()
is sufficient for basic random number generation, it produces pseudorandom numbers with a finite cycle. When generating large volumes of random numbers, periodic patterns may emerge, making it unsuitable where perfect randomness is required.
Issues in Multithreaded Environments
In multithreaded environments, using rand()
may result in multiple threads sharing the same seed value, causing them to produce identical random numbers. To avoid this, each thread should use a unique seed value.
Using High-Quality Random Number Generators
C++ and other languages provide higher-quality random number generators. While options in C are limited, it is recommended to use more advanced algorithms such as the random()
function or the Mersenne Twister (mt19937
).
6. Conclusion
In this article, we explained how to generate random numbers in C, provided actual code examples, and showed practical applications. The rand()
function is very useful for basic programs, but caution is needed when true randomness is required.