Searching

AP Computer Science A· difficulty 3/5

int[] a = {2, 4, 6, 8, 4};
int target = 4;
int idx = -1;
for (int i = 0; i < a.length; i++) {
  if (a[i] == target) {
    idx = i;
    break;
  }
}
System.out.println(idx);

What is printed?

  • A

    0

  • B

    1

    check_circle
  • C

    4

  • D

    -1

Explanation

With a break, the loop stops at the first match. The first 4 is at index 1.

Want 10 more like this — adaptive to your weak spots?

Related questions