Generate Random Numbers in C – rand() and srand() Explained

This C program to generate random numbers uses the standard library functions rand() and srand(). rand() returns a pseudo-random integer between 0 and RAND_MAX (at least 32767). “Pseudo-random” means the sequence is determined by a starting value called the seed. Seeding with time(NULL) ensures a different sequence every time the program runs.

Key Functions

Function Header Purpose
srand(seed) <stdlib.h> Sets the starting point for the random sequence. Call once before any rand() calls.
rand() <stdlib.h> Returns the next pseudo-random integer in [0, RAND_MAX].
time(NULL) <time.h> Returns the current time as a number. Used as a seed so each program run gets a different sequence.

C Program to Generate Random Numbers

/* Generate random numbers in C using rand() and srand()
 * Compile: gcc -ansi -Wall -Wextra random_num.c -o random_num */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int i, num;

    printf("How many random numbers to generate? ");
    scanf("%d", &num);

    if (num <= 0) {
        printf("Please enter a positive integer.\n");
        return 1;
    }

    /* seed with current time so numbers differ on each run */
    srand((unsigned int)time(NULL));

    printf("\n%d random numbers (full range 0 to RAND_MAX):\n", num);
    for (i = 0; i < num; i++)
        printf("  [%d] %d\n", i + 1, rand());

    printf("\nControlled ranges (examples):\n");
    printf("  0 to 99  : %d\n", rand() % 100);
    printf("  1 to 10  : %d\n", rand() % 10 + 1);
    printf("  50 to 100: %d\n", rand() % 51 + 50);

    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra random_num.c -o random_num
./random_num

Sample Output

How many random numbers to generate? 5

5 random numbers (full range 0 to RAND_MAX):
  [1] 1804289383
  [2] 846930886
  [3] 1681692777
  [4] 1714636915
  [5] 1957747793

Controlled ranges (examples):
  0 to 99  : 42
  1 to 10  : 7
  50 to 100: 83

Your output will differ because time(NULL) produces a different seed each run.

Generating Numbers in a Specific Range

The general formula to get a random integer in [low, high] (inclusive):

int r = rand() % (high - low + 1) + low;
Range Expression Example result
0 to 9 rand() % 10 0, 1, …, 9
1 to 10 rand() % 10 + 1 1, 2, …, 10
0 to 99 rand() % 100 0, 1, …, 99
50 to 100 rand() % 51 + 50 50, 51, …, 100
−5 to 5 rand() % 11 - 5 −5, −4, …, 5

Code Explanation

  • srand((unsigned int)time(NULL)) — the cast to unsigned int is required because srand() takes unsigned int but time() returns time_t. The cast silences the compiler warning without changing behavior.
  • Call srand() once, rand() many times — calling srand() inside the loop would reseed on each iteration, which defeats the purpose. In the worst case, if the loop runs fast enough, every call to time(NULL) returns the same value, giving you the same “random” number every iteration.
  • rand() % n modulo bias — when RAND_MAX + 1 is not divisible by n, the lower values in [0, n−1] appear slightly more often than the higher values. For most educational programs this difference is negligible, but for cryptographic or statistical work, use a more uniform algorithm.
  • RAND_MAX — defined in <stdlib.h>, guaranteed to be at least 32767. On Linux it is typically 2147483647 (2³¹ − 1). Print it with printf("%d\n", RAND_MAX); to see the value on your system.

Fixed Seed for Reproducible Output

To get the same sequence every run (useful for testing and debugging), use a fixed seed:

srand(42);   /* same sequence every run */

Replace 42 with any constant. Seeding with 0 or 1 also works. Remove the time(NULL) call completely when you need reproducible output.

What This Program Teaches

  • Pseudo-random vs truly randomrand() produces a deterministic sequence from its seed. The same seed always produces the same numbers. Time-based seeding makes each run appear different, but this is not cryptographically random.
  • Seed once, generate many — the correct pattern is to call srand() once at the start of the program, then call rand() as many times as needed. Reseeding mid-program breaks the statistical properties of the generator.
  • Modulo for range mappingrand() % n maps the full RAND_MAX range onto [0, n−1]. Understanding why this works (and its slight bias) is important for any program that relies on randomness.
  • Fixed seed for test reproducibility — replacing time(NULL) with a constant makes random-dependent bugs reproducible, which is a crucial debugging technique.

Related Programs

Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
 | 
C Programming: A Modern Approach — K.N. King (India) |
(US)

Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>