85.0k views
4 votes
Which of the following code produce a random number between 0 to 123 (0 and 123 is included)? Your answer: a. int r = rand () % 124; b. int r = rand () % 123; c. int r= (rand () % int r = (rand () % d. int r= (rand() % 124) - 1; 122) + 1; 123) + 1;

User Jagannath
by
7.3k points

1 Answer

4 votes

Answer:

The correct option to produce a random number between 0 to 123 (including 0 and 123) is option d: int r= (rand() % 124) - 1;.

Option a generates a number between 0 to 123 (including 0 but excluding 123).

Option b generates a number between 0 to 122 (excluding both 123 and 0).

Option c is invalid code.

Option d generates a number between -1 to 122 (including -1 and 122), but by subtracting 1 from the modulus operation, we shift the range down by 1, giving us a number between 0 and 123 (including both 0 and 123). Here's an example code snippet:

#include <stdlib.h>

#include <stdio.h>

#include <time.h>

int main() {

srand(time(NULL)); // Initialization, should only be called once.

int r= (rand() % 124) - 1;

printf("%d", r);

return 0;

}

Step-by-step explanation:

User Kati
by
9.3k points