<http://lib.cnfolio.com/ENG421PseudoRandomNumbers>
Introduction to Algorithms and Programming

Pseudo random numbers



Generate pseudo random numbers


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int main( void )
  6. {
  7.   int number;
  8.  
  9.   /* Initialise the random number generation with the current time
  10.      This only needs to be called once. */
  11.   srand( time( 0 ) );
  12.  
  13.   /* The rand() function is called each time a new random number is required. */
  14.   number = rand();
  15.  
  16.   printf( "%d", number );
  17. }




Generate pseudo random numbers between 1 and 100


The modulus operator is commonly used to help generate pseudo random numbers that are always between 1 and 100.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int main( void )
  6. {
  7.   int number;
  8.  
  9.   /* Initialise the random number generation with the current time
  10.      This only needs to be called once. */
  11.   srand( time( 0 ) );
  12.  
  13.   /* The rand() function is called each time a new random number is required.
  14.      The modulus operator generates a number between 0 and 99. */
  15.   number = rand() % 100;
  16.  
  17.   /* Manually add 1 to bring the range between 1 and 100. */
  18.   number++;
  19.  
  20.   printf( "%d", number );
  21. }




Generate pseudo random numbers for small value ranges


A loop can be used to reject the unwanted high numbers until a pseudo number is found in the small value range.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int main( void )
  6. {
  7.   int number;
  8.  
  9.   /* Initialise the random number generation with the current time
  10.      This only needs to be called once. */
  11.   srand( time( 0 ) );
  12.  
  13.   /* The rand() function is called and rejected in a loop until a
  14.      number is found that is low enough to fit in the required range.
  15.      In this example, the target range is 0-5 */
  16.   do
  17.   {
  18.     number = rand();
  19.   } while ( number >= 5 );
  20.  
  21.   /* Manually add 1 to bring the range between 1 and 6. */
  22.   number++;
  23.  
  24.   printf( "%d", number );
  25. }




Reference documentation:





Practice examples


  1. Write a program to randomly select one color from the range of colors available in a rainbow.
  2. Write a program to randomly select one color using the RGB web colors format.
  3. Write a program to generate the age of a random student or staff in the university population.