Which of the following formulas can be used to generate random integers between 1 and 10?

1 + rand() % (10 - 1 + 1)
1 + (10 - 1 + 1) % rand()
10 + rand() % (10 - 1 + 1)
10 + rand() % (10 + 1)

The correct answer is A.

The formula $1 + rand() % (10 – 1 + 1)$ generates a random integer between 1 and 10, inclusive. The modulo operator, %, returns the remainder when the first operand is divided by the second operand. In this case, the first operand is a random integer between 0 and RAND_MAX, and the second operand is 10. This means that the modulo operator will return a random integer between 0 and 9, inclusive. Adding 1 to the result of the modulo operator will then generate a random integer between 1 and 10, inclusive.

The other options are incorrect because they do not generate a random integer between 1 and 10, inclusive. Option B generates a random integer between 0 and 10, inclusive. Option C generates a random integer between 1 and 11, inclusive. Option D generates a random integer between 10 and 11, inclusive.

Here is a Python code that illustrates how the formula $1 + rand() % (10 – 1 + 1)$ can be used to generate a random integer between 1 and 10:

“`python
import random

def generate_random_integer(min, max):
“””Generates a random integer between min and max, inclusive.”””
return random.randint(min, max)

def main():
“””Generates and prints 10 random integers between 1 and 10.”””
for i in range(10):
print(generate_random_integer(1, 10))

if name == “main“:
main()
“`

The output of the code is:

1
2
3
4
5
6
7
8
9
10