Possible Duplicates:
Generate Random numbers uniformly over entire range
In C, how do I get a specific range of numbers from rand()?
i want to generate random number in C. It has rand() and srand() function in stdlib.h But it gives me very large number. But I want only number b/w 1 to 10. So, is it possible and if yes then how? If is possible to generate character from a-z randomly.
The simplest way is to use the modulo operator to cut down the result to the range you want. Doing
rand() % 10will give you a number from 0 to 9, if you add 1 to it, i.e.1 + (rand() % 10), you’ll get a number from 1 to 10 (inclusive).And before others complain, this may dilute the random distribution, nevertheless, it should work fine for simple purposes.