
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generating random number in a range in C
To print random numbers within a range, we will have two input variables where we need to set the maximum and minimum values. Using these two values, we can display a random value within the specified range.
Example
Following is the input-output statement to understand the range of a random number:
Input: min = 4, max = 14 Output: 8, 10, 7
Explanation: Any numeric value between 4 and 14 can be displayed in the specified range.
Generate Random Number Within a Range Using rand() with Modulus
The rand() function generates the random number while modulus operator return the remainder. To calculate the range of random number we use the following formula:
num = min + rand() % (max - min + 1)
Here,
- min: This shift the range to start from the min. The min define the minimum value. Make sure the final value is between min and max.
- rand() % (max - min + 1) : This calculate the random number and the expression are mathematically represented.
Based on above statement,
// 37 % 11 -> remainder is 4 num = 4 + (37 % (14 - 4 + 1)); // num = 8 num = 4 + 4;
Example
Following is the C program to print the random number in a range.
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); int min = 4, max = 14; for (int i = 0; i < 3; i++) { int num = min + rand() % (max - min + 1); printf("%d ", num); } return 0; }
The above program produces the following result:
13 13 11
Generate Random Number Within a Range Using random() Function
The random() function is also similar to the rand() function to find a random integer value. The program logic is almost the same, only the function has changed.
Example
In this example, we print the total of 5 random values that range between 3 and 19.
#include<stdio.h> #include<stdlib.h> #include<time.h> int main() { srandom(time(NULL)); int min = 3, max = 19; for (int i = 0; i < 5; i++) { int num = min + (random() % (max - min + 1)); printf("%d ", num); } return 0; }
The above program produces the following result:
17 9 7 13 15