Searching

AP Computer Science A· difficulty 2/5

int[] a = {3, 7, 1, 9, 4};
int target = 9;
int idx = -1;
for (int i = 0; i < a.length; i++) {
  if (a[i] == target) { idx = i; break; }
}

What is the value of idx after the loop?

  • A

    4

  • B

    0

  • C

    3

    check_circle
  • D

    -1

Explanation

Linear search finds 9 at index 3, so idx is set to 3 and the loop breaks.

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

Related questions