Doubt in code with rand() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Doubt in code with rand()

Why is the output of this code 135? ... for(int i=1; i<=6; i+=2); cout << (i + rand()%1); ...

9th Dec 2017, 11:55 AM
Javier Monreal Trigo
Javier Monreal Trigo - avatar
2 Answers
+ 3
It is because everything modulo 1 is 0. Try to divide any number by 1 and see, what is the remainder. It is always 0, so you are basically adding 0 to your numbers 1, 3 and 5. If you put newline inside the loop, the output will be: 1 3 5
9th Dec 2017, 12:02 PM
Daniel Oravec
Daniel Oravec - avatar
+ 10
any number % 1 is 0 because any number is divided with 1
9th Dec 2017, 12:00 PM
Vukan
Vukan - avatar