TechnologyA Random Function in C with ranges

A Random Function in C with ranges

We all know the rand() function in C. It returns a random number in the range [0,RAND_MAX]

Syntax : int j = rand();

Now RAND_MAX can vary based on the computer and operation system. TO see what is the value of RAND_MAX in your system you can use

printf("Rand Max = %u\n",RAND_MAX);

RAND_MAX is a key word and it will display the range for you.  As we see we do not have any control over this range of [0, RAND_MAX]

What if you wanted to get random numbers between 100 and 1000 only ?

Below is a small function that can help. It takes the range min and max and returns a random number in that range.

Note when you say Random numbers in range [10, 100] both 10 and 100 are included in the range of random numbers

Below is the function:

int random_range(int min, int max) {
	int random_num;
	int ranged_random_num;
	if(max >= min) {
		random_num = rand();
		ranged_random_num = min + random_num % (max - min + 1);
		return ranged_random_num;
	}
}

By modifying the factor [max – min + 1] you can include/exclude boundary values

A small C program to generate 100 random numbers in between 75 and 825 would look like below

#include "stdio.h"
#include "stdlib.h"

int random_range(int,int);

int main() {

 int i,j,k;
 for(j = 0; j<100; j++)
 printf("Random Number = %d\n",random_range(75,825));

 printf("\n");
 return 0;
}

int random_range(int min, int max) {
 int random_num;
 int ranged_random_num;
 if(max >= min) {
 random_num = rand();
 ranged_random_num = min + random_num % (max - min + 1); 

 return ranged_random_num;
 }
}

Categories: Technology

Comments

No Comments Yet. Be the first?

Post a comment

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