C

How To Generate Random Numbers in C With a Range

In this tutorial, we are going to see how to generate random numbers in C with a range. The rand() function is used in C to generate a random integer. In the following code we have used rand() % 100 + 1 to generate random numbers between 1 and 100. So to generate random numbers between 1 and 10 use rand() % 10 + 1.
 

How To Generate Random Numbers in C With a Range
#include <stdio.h>
#include <stdlib.h>
 
int main() {
  int i, n;
 
  printf("10 random numbers in [1,100]\n");
 
  for (i = 1; i <= 10; i++) {
    n = rand() % 100 + 1;
    printf("%d\n", n);
  }
 
  return 0;
}

Output:

10 random numbers in [1,100]
84
87
78
16
94
36
87
93
50
22

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *