What does this particular code fragment do?

what will (rand()%4)+1; do in the code?

I know :

num1 = rand()%100; - generate numbers randomly from 0-99
&
num2 = rand()%100+1; - generates numbers randomly from 1 - 100

How about (rand()%4)+1 ?
The modulus operator (%) returns the remainder that you get when you divide the first number by the second.
So for instance, 7 % 3 == 1 because when you do 7/3, you get 2 with a remainder of 1.
It follows that when you do a % b, the answer is always going to be between 0 and b - 1 (assuming both numbers are positive).

So rand() % 4 generates a random number and returns the remainder when that number is divided by 4, which will be a random number between 0 and 3.
So (rand() % 4) + 1 gives you a random number between 0 and 3, plus 1, so that will be a random number between 1 and 4.
Topic archived. No new replies allowed.