Generate a RANDOM NO. in a given RANGE – C PROGRAM

In the last few posts I have written about generating random numbers and using them to simulate a coin flip or a 1-d random walk.
In this post I will show you how to generate a random number in a given range.

CODE:

/**********************************************
****GENERATE RANDOM NUMBERS IN A GIVEN RANGE***
***********************************************/
#include<stdio.h>
#include<math.h>
/**Function that generates a random number.
Parameters: 
r0: initial (first) seed
a: scale factor , so that a*r0 give the first random number
m: gives the max. value of random numbers that can be generated (m-1)
c: additional displacement(offset) factor
**/
int rand(int r0, int a, int m, int c){
	int r1=(a*r0+c)%m;
	return r1;
}
/**Function that generates random numbers in a given range: [min,max], given a seed r0, and stores them in an array that is passed as an argument.
Parameters:
r0: initial (first) seed
a: scale factor , so that a*r0 give the first random number
m: gives the max. value of random numbers that can be generated (m-1)
c: additional displacement factor
n: no. of random numbers to be generated
x[n]: array that will store the random numbers
min: lower limit for random nos.
max: upper limit for random nos.
**/
void randomNos(int r0, int a, int m, int c, int n, int x[n], int min, int max){
	int r1=rand(r0,a,m,c);
	int r2=min+((max-min+1)*r1)/m;
	int i;
	for(i=0;i<n;i++){
		x[i]=r2;
		r1=rand(r1,a,m,c);
		r2=min+((max-min+1)*r1)/m;
	}
}
main(){
	int min, max, n, a=1093, m=86436, c=18257, r0=43;
	printf("Enter the lower limit:\n");
	scanf("%d",&min);
	printf("Enter the higher limit:\n");
	scanf("%d",&max);
	printf("Enter the no. of random numbers required:\n");
	scanf("%d",&n);
	int random[n];
	randomNos(r0, a, m, c, n, random, min, max);
	int i;
	printf("The random numbers between %d and %d are:\n",min, max);
	for(i=0;i<n;i++){
		printf("%d\n",random[i]);
	}
}

OUTPUT:

Sample run 1

I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.



Leave a Reply

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