Random numbers generating program in C

In this C programming article we will learn to make random numbers generating in C. We can print random number between two range. Here in the program we will print random number between two range. Let’s see some random number generating program bellow.

C program to generate random numbers

// random number generating program in c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void random_generator(int min, int max, int counter){
  int k;
  for(k = 0; k < counter; k++){
    int rand_num = (rand() % (max - min + 1)) + min;
    printf("%d\n", rand_num);
  }
}

int main(){
  int lower_num, upper_num, c = 1;

  printf("Enter lower and upper limit : \n");
  scanf("%d %d", &lower_num, &upper_num);

  printf("\nGenerated random number is = ");

  srand(time(0));   // using current time for random numbers

  random_generator(lower_num, upper_num, c);

  return 0;
}

Output of random number program:

random-number-in-c-generating-random-number-in-c

Generate several random numbers

// many random number generating program

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void random_generator(int min, int max, int counter, int num){
  int j, k;
  for(j = 1; j <= num; j++){
    for(k = 0; k < counter; k++){
      int rand_num = (rand() % (max - min + 1)) + min;
      printf("%d\n", rand_num);
    }
  }
}

int main(){
  int n, lower_num, upper_num, c = 1;

  printf("Enter lower and upper limit : \n");
  scanf("%d %d", &lower_num, &upper_num);

  printf("Enter how many random numbers you want : ");
  scanf("%d", &n);

  printf("\nGenerated random numbers are : \n");

  srand(time(0));

  random_generator(lower_num, upper_num, c, n);

  return 0;
}

Output of random number generator program:

Enter lower and upper limit :
20 80
Enter how many random numbers you want : 5

Generated random numbers are :
36
60
53
23
34

You can also make the following program to print random numbers.

#include <stdio.h>
#include <stdlib.h>

int main(){
  int num, r, max;

  printf("Enter maximum limit of random number : ");
  scanf("%d", &max);

  printf("\nEnter how many number you want : ");
  scanf("%d", &num);

  printf("\n%d random numbers between 0 to %d are : \n\n", num, max);

  while(num--){
    r = rand()%max + 1;
    printf("%d ", r);
  }
  getch();
  return 0;
}

The program will give following output when you compile and run it.

Enter maximum limit of random number : 50

Enter how many number you want : 10

10 random numbers between 0 to 50 are :

42 18 35 1 20 25 29 9 13 15

All these program may print different output when you run them to your computer. Because every time they will print different random numbers. So, don’t worry about that.

Previous pageSwap string

Next pagePrint date and time