Create pseudo-random integer - C Data Structure

C examples for Data Structure:Algorithm

Description

Create pseudo-random integer

Demo Code

#include <stdio.h>

unsigned long int next = 1;

/* pseudo-random integer on 0..32767 */
int rand(void)
{
    next = next * 1234567245 + 12345;/*from ww  w .jav  a  2  s. c  o m*/
    return (unsigned int)(next/65536) % 32768;
}

/* srand:  set seed for rand() */
void srand(unsigned int seed){
    next = seed;
}

int main()
{
    for (int i = 1; i < 10; i++)
        printf(" %d", rand());

    printf("\n");
    
    srand(1);
    for (int i = 1; i < 10; i++)
        printf(" %d", rand());

    srand(1);
    for (int i = 1; i < 10; i++)
        printf(" %d", rand());

    srand(2);
    for (int i = 1; i < 10; i++)
        printf(" %d", rand());

    printf("\n");

    return 0;
}

Result


Related Tutorials