Back to C Programming
2026-07-125 min read

C - Random Number Generation

Learn C - Random Number Generation step by step with clear examples and exercises.

Why This Matters

Random number generation is an essential aspect of programming, as it allows us to create unpredictable outcomes in our applications. These unpredictable outcomes can make our programs more dynamic, engaging, and realistic. In this lesson, we'll learn how to generate random numbers in C, understand common mistakes, and practice with some questions.

Importance of Random Number Generation

Random number generation is crucial for various scenarios such as game development, simulations, cryptography, and statistical analysis. It helps create unpredictable outcomes, making our applications more engaging and realistic. In addition, it's essential for generating random seeds to ensure that the results of a program are not always the same, which is crucial for testing purposes.

Prerequisites

Before diving into random number generation, you should have a good understanding of C programming basics, including variables, data types, functions, and control structures like loops and conditional statements. Familiarity with pointers can also be beneficial when working with more advanced random number generation techniques.

Core Concept

In C, the rand() function is used to generate random numbers. This function generates a sequence of pseudo-random numbers. The sequence starts from a seed value and advances linearly with each call. If you don't specify a seed, the system clock will be used as the default seed, ensuring that different programs have different sequences.

The rand() function returns an integer between 0 and RAND_MAX (a predefined constant). To get a random number within a specific range, we can use modulo arithmetic:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
srand(time(NULL)); // seed the random number generator with current time
int randomNumber = rand() % 100; // generate a random number between 0 and 99
printf("Random number: %d\n", randomNumber);
return 0;
}

In this example, we include the ` and headers to access the rand() function and seed the random number generator with the current time using srand(time(NULL)). We then generate a random number between 0 and 99 by taking the remainder of dividing the result of rand()` by 100.

Understanding Pseudo-Random Numbers

It's essential to understand that the numbers generated by the rand() function are pseudo-random, meaning they appear random but are not truly random as they follow a specific pattern. For truly random numbers, you would need to use hardware-based random number generators or external sources of randomness, such as noise sensors or network traffic.

Worked Example

Let's create a simple program that generates 10 random numbers between 1 and 50, and calculates their sum:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
srand(time(NULL)); // seed the random number generator with current time
int sum = 0;
for (int i = 0; i < 10; i++) {
int randomNumber = rand() % 50 + 1; // generate a random number between 1 and 50
printf("Random number: %d\n", randomNumber);
sum += randomNumber;
}
printf("Sum of random numbers: %d\n", sum);
return 0;
}

In this example, we generate 10 random numbers between 1 and 50 using a for loop. We calculate the sum of these numbers and print both the individual random numbers and their total.

Common Mistakes

  1. Not seeding the random number generator: If you don't seed the random number generator, you may get the same sequence of random numbers every time you run your program.
  2. Using rand() without modulo arithmetic: When using rand(), it's essential to use modulo arithmetic to ensure that the generated number falls within the desired range.
  3. Not including necessary headers: Make sure to include both ` and to access the rand()` function and seed the random number generator.
  4. Using an incorrect seed value: Using a constant or predictable seed value can lead to the same sequence of random numbers every time the program is run. It's best to use the current time as the seed value, as shown in our examples.
  5. Not considering the range of rand(): The rand() function returns an integer between 0 and RAND_MAX (a predefined constant). If you need a specific range, make sure to adjust your code accordingly using modulo arithmetic or adding a constant to the result of rand().
  6. Not handling edge cases: When generating random numbers within a specific range, be aware of the edge cases where the minimum value can be equal to the maximum value. In such cases, you may need to adjust your code to ensure that the generated number is always within the desired range.

Practice Questions

  1. Write a program that generates 5 random numbers between 0 and 100 and calculates their average.
  2. Modify the previous example to generate random numbers within a user-defined range (e.g., between 10 and 30).
  3. Create a game that generates a random number between 1 and 100, and asks the user to guess the number. The program should provide feedback on whether the user’s guess is too high, too low, or correct.
  4. Modify the previous example to generate random numbers with a specific distribution (e.g., more likely to generate numbers close to the middle of the range).
  5. Research and implement a method for generating truly random numbers in C using hardware-based random number generators or external sources of randomness.

FAQ

How does the rand() function work?

The rand() function generates a sequence of pseudo-random numbers based on a seed value. It returns an integer between 0 and RAND_MAX (a predefined constant). To get a random number within a specific range, we can use modulo arithmetic.

Can I generate truly random numbers in C?

No, the rand() function generates pseudo-random numbers based on a seed value. While these numbers appear random, they are not truly random as they follow a specific pattern. For truly random numbers, you would need to use hardware-based random number generators or external sources of randomness, such as noise sensors or network traffic.

Why should I seed the random number generator with the current time?

Seeding the random number generator with the current time ensures that each program run produces a different sequence of pseudo-random numbers. This is essential for ensuring that test cases are not always the same and that the generated numbers are truly unpredictable.

What is the difference between rand() and srand()?

rand() generates a random number, while srand() seeds the random number generator with a specified value. The seed value determines the starting point of the sequence of pseudo-random numbers generated by rand().