208k views
2 votes
Which generates a random integer in the range 18 - 30?

A. (rand() % (30 - 18 + 1)) + 18
B. rand() % 31
C. rand() % 30
D. (rand() % (30 - 18) ) + 18
E. rand() % (30 -18)

User Yo Chauhan
by
7.9k points

1 Answer

3 votes

Final answer:

The correct option for generating a random integer between 18 and 30 inclusive is A. It leverages the modulus operator to ensure the number falls within the required range and shifts it accordingly by adding the starting value (18) of the range.

Step-by-step explanation:

The question refers to generating a random integer within a specific range using a random number function, commonly used in computer programming. The correct option that generates a random integer between 18 and 30 inclusive is A. The expression (rand() % (30 - 18 + 1)) + 18 uses the modulus operator to obtain a remainder that falls within the range of 0 to 12 (which is 30 - 18 + 1), and then adds 18 to shift the range to 18 to 30.

Options B, C, and E do not add the starting value of the range (18), and thus, their outcome will not be within the required range. Option D is close but misses by one because it doesn't account for the inclusive nature of '30' since it uses (30 - 18) instead of (30 - 18 + 1).

User Sarfata
by
8.2k points