Learn AP Comp Sci

Problem of the Day

Monday, April 22, 2024


Problem:

Consider the following code segment, which prints out a series of asterisks.

int n = 3;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print("*");
}
}

What is the big-O performance of this code segment?

  1. O(1) - constant
  2. O(n) - linear
  3. O(n2) - quadratic
  4. O(2n) - exponential

Show solution:

The correct answer is c. Nested loops such as this are often quadratic in nature, and thus not ideal for scaling up to large values of n.