Learn AP Comp Sci

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 minimum number of times the letter "r" will be printed?

  1. 3 times
  2. 4 times
  3. 6 times
  4. 8 times

Show solution:

The correct answer is c. The minimum number of times the outer i loop will run is twice, while the minimum number of times the inner j loop can run is three times. Thus, the minimum number of times "r" will be printed is 2 × 3 = 6.