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.