rand

Mathematics Functions

Gets a random integer between 0 and 32767.

int rand( void ); 

Before invoking rand, call srand to seed the pseudo-random number generator.

Return Values

Returns a pseudo-random integer in the range 0 to 32767.

Examples

Example 1

The following example generates a random number restricted to a specific zero-based range using the mod (%) operator.

    //srand is called before rand
    srand(time(NULL));
    // Generate a random number from 0-99  
    lr_output_message("A number between 0 and 99: %d\n", rand() % 100);
Example: Output:
Action.c(7): A number between 0 and 99: 72

Example 2

The following example generates a random number, rNum, between 20 and 29 using the mod (%) operator and addition.

    int rNum;
    //srand is called before rand
    srand(time(NULL));
/* The order of evaluation is first rand(), then the modulus, then the addition. The command below is equivalent to :
    rNum = rand() % 10; 
 rNum is now a number between 0-9
    rNum += 20;
        rNum is now between 20 and 29
*/
    rNum= rand() % 10 + 20;