Problem of the Day
Problem:
Consider the following code segment.
int a = (int) (Math.random() * 3 + 2);
for (int i = 1; i <= a; i++)
{
int b = (int) (Math.random() * 2 + 4);
for (int j = 2; j <= b; j++)
{
System.out.print("r");
}
}
What is the maximum number of times the letter "r
" will be printed?
- 16 times
- 20 times
- 25 times
- 30 times
The correct answer is a. The maximum number of times the outer i
loop will run is four times (going from 1, inclusive to the maximum random value of 4, inclusive), and the maximum number of times the inner j
loop can run is four times (going from 2, inclusive, to a maximum random value of 5, inclusive). Thus, the minimum number of times "r
" will be printed is 4 × 4 = 16.