You are here

C program to generate random numbers

C program to generate pseudo-random numbers using rand and random function (Turbo C compiler only). As the random numbers are generated by an algorithm used in a function they are pseudo-random, this is the reason that word pseudo is used. Function rand() returns a pseudo-random number between 0 and RAND_MAX. RAND_MAX is a constant which is platform dependent and equals the maximum value returned by rand function.

C programming code using rand

We use modulus operator in our program. If you evaluate a % b where a and b are integers then result will always be less than b for any set of values of a and b. For example
For a = 1243 and b = 100
a % b = 1243 % 100 = 43
For a = 99 and b = 100
a % b = 99 % 100 = 99
For a = 1000 and b = 100
a % b = 1000 % 100 = 0

In our program we print pseudo random numbers in range [0, 100]. So we calculate rand() % 100 which will return a number in [0, 99] so we add 1 to get the desired range.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main() {
  5.   int c, n;
  6.  
  7.   printf("Ten random numbers in [1,100]\n");
  8.  
  9.   for (c = 1; c <= 10; c++) {
  10.     n = rand() % 100 + 1;
  11.     printf("%d\n", n);
  12.   }
  13.  
  14.   return 0;
  15. }

If you rerun this program, you will get the same set of numbers. To get different numbers every time you can use: srand(unsigned int seed) function; here seed is an unsigned integer. So you will need a different value of seed every time you run the program for that you can use current time which will always be different so you will get a different set of numbers. By default, seed = 1 if you do not use srand function.

C programming code using random function (Turbo C compiler only)

Function randomize is used to initialize random number generator. If you don't use it, then you will get same random numbers each time you run the program.

  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <stdlib.h>
  4.  
  5. int main()
  6. {
  7.    int n, max, num, c;
  8.  
  9.    printf("Enter the number of random numbers you want\n");
  10.    scanf("%d", &n);
  11.  
  12.    printf("Enter the maximum value of random number\n");
  13.    scanf("%d", &max);
  14.  
  15.    printf("%d random numbers from 0 to %d are:\n", n, max);
  16.    
  17.    randomize();
  18.  
  19.    for (c = 1; c <= n; c++)
  20.    {
  21.       num = random(max);
  22.       printf("%d\n",num);        
  23.    }
  24.  
  25.    getch();
  26.    return 0;
  27. }