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 it here.

The output of the example looks like this:

0:1804289383
1:846930886
2:1681692777
3:1714636915
4:1957747793
0:1529532811
1:335710285
2:897970550
3:1928278434
4:1701785123

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer