1

I'm trying to generate a 4 digits number using C. I think that we are able to use the 'rand' function, however it generates random numbers with random digits, not only 4. We have to generate a 4 - digits number.

Any help? Thanks in advance!

user2248453
  • 21
  • 1
  • 2
  • check this for 4digit only http://stackoverflow.com/questions/19051860/generate-random-numbers-with-fixed-digits-length – Francis Saul Dec 07 '15 at 08:56

2 Answers2

3

you can use this if it's "randomness" isn't important:

1000+(rand()%9000)
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
hassan arafat
  • 657
  • 5
  • 15
2

Please try this one, i hope it will help you. arc4random uses a better pseudo random number generator than random: it generates a statistically more uniform, less predictable distribution; is based on a larger range of possible numbers. Also, ar4random doesn't need to be initialized as its seed is auto-generated.

E.g. generate numbers :1000~9999

int randomID = arc4random() % 9000 + 1000;

generate numbers :1000~2999

int randomID = arc4random() % 2000 + 1000;
Michele Giuseppe Fadda
  • 1,302
  • 1
  • 17
  • 26
Mohd Aman
  • 224
  • 1
  • 3
  • 13