Example of random number generation in C

This C program demonstrates random number generation using random. It also demonstrates seeding the random number generator using time and srandom.

/* "random" is declared in stdlib.h. */
#include <stdlib.h>
/* This program uses "time" to seed the random number generator. */
#include <time.h>
#include <stdio.h>

int main ()
{
    int i;
    /* This prints the same random numbers each time. */
    for (i = 0; i < 5; i++) {
        printf ("%d:%ld\n", i, random ());
    }
    /* To get different random numbers, use "srandom" to seed the
       random number generator with the current time in seconds. */
    srandom (time (0));
    /* This prints different random numbers each time. */
    for (i = 0; i < 5; i++) {
        printf ("%d:%ld\n", i, random ());
    }
    return 0;
}

(download)

The output of the example looks like this:

0:1804289383
1:846930886
2:1681692777
3:1714636915
4:1957747793
0:476989227
1:2118851303
2:1402472888
3:804484447
4:570289567


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer