Why 1 is added with (rand()%range) ? And why do we use module % between rand() and range ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why 1 is added with (rand()%range) ? And why do we use module % between rand() and range ?

This program has to give an output of 4 Digit PIN number randomly. https://code.sololearn.com/cxM8ELNcpYjd/?ref=app

3rd Jul 2022, 12:11 PM
Aftab Qureshi
Aftab Qureshi - avatar
2 Answers
+ 3
You need to include the time header and throw time inside the call to srand(). It keeps it more "random", with yhe same seed, you will get the same values every time. You use modulo because numbers generated are random, ex. 3482. To get a single digit, you use modulo with your limit. https://code.sololearn.com/cI2s5hQ4R7EV/?ref=app
3rd Jul 2022, 12:34 PM
Slick
Slick - avatar
+ 2
rand() returns a long random There range is for generate numbers between 1 to range (inclusive). rand() % range returns a number between 0 to range-1. So add one to get number between 1 to range. If you want 0 to range-1, don't add one. Ex: if rand() returns 12345898 and if range=5 then rand()%range returns 3 adding 1 results 4.. Hope it helps..
3rd Jul 2022, 12:37 PM
Jayakrishna 🇮🇳