Link to home
Start Free TrialLog in
Avatar of gaurav_chikara
gaurav_chikara

asked on

How to generate a Random no with in a Range

Hi
Since I am a novice in this area and I donot know much about the random generation concept Can anyone pls let me know by any sample whether there is any way by which we can generate a random number with in a given specified range

Thankx in advance
Avatar of posternb
posternb

The standard way of generating 'random' numbers in C is the rand() function.  This function returns any random number so to get it within a certain range take the modulus of it. i.e.

rand()%10 returns numbers between 0-9, inclusive

I quoted 'random' above because the numbers aren't truly random, in fact you'll get the same string of numbers for any given seed.  You seed the generator by calling srand( seed ).  A popular technique is to seed with the current time, so you'll get a new sequence everytime you run the program (at a different time of course).

srand( time(0) );
ASKER CERTIFIED SOLUTION
Avatar of gj62
gj62

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Random number generation is actually a very complicated task. The inbuilt C functions (rand(), srand(), etc) are notorious for generating poor random numbers. The book "Numerical Recipes in C" has lots on information on generating "good" random numbers with source code. Check out chapter 7 at:

http://www.library.cornell.edu/nr/bookcpdf.html

Avatar of gaurav_chikara

ASKER

Your solution really worked
I must say you are a C wizard
thankx for ur answer