Thread: How does rand() and srand() together?

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    144

    How does rand() and srand() together?

    Can someone verify if my understanding is correct?

    I have read some document that says:
    rand() function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX. Returns a pseudo-random integer.

    srand(seed) : uses the argument for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand.

    Questions:
    1. How many numbers are generated when srand is seeded. For example, in the following code, it seems as if srand() has generated a huge list of numbers and rand() returns a number based on some formula. Is this right?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
    	srand(1);
    
    	printf("%d\n", rand());
    	printf("%d\n", rand());
    	printf("%d\n", rand());
    	printf("%d\n", rand());
    	printf("%d\n", rand());
    	printf("%d\n", rand());
    
    	getchar();getchar();
    	return 0;
    
    
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    All that srand() does is initialize a static parameter to the rand() function called. It doesn't generate a bunch of numbers. Here's an example implementation (from the C standard).
    Code:
    static unsigned long int next = 1;
    
    int rand(void) // RAND_MAX assumed to be 32767
    {
        next = next * 1103515245 + 12345;
        return (unsigned int)(next >> 16) & 0x7fff;
    }
    
    void srand(unsigned int seed)
    {
        next = seed;
    }
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    microsoft version:
    Code:
    int rand(void){
        return(( (seed = seed * 214013L + 2531011L) >> 16) & 0x7fff );
    }
    wiki article with a list of examples:

    https://en.wikipedia.org/wiki/Linear...tial_generator

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. srand and rand
    By pobri19 in forum C++ Programming
    Replies: 4
    Last Post: 10-12-2008, 07:09 AM
  2. Rand and srand
    By JFonseka in forum C Programming
    Replies: 5
    Last Post: 02-26-2008, 10:36 PM
  3. srand() and rand()
    By Mr.Sellars in forum C++ Programming
    Replies: 3
    Last Post: 08-12-2007, 03:19 PM
  4. rand and srand
    By the pooper in forum C Programming
    Replies: 34
    Last Post: 10-19-2005, 07:27 AM
  5. srand() or rand()???
    By bajanstar in forum C Programming
    Replies: 4
    Last Post: 03-04-2005, 12:58 PM