Searching

AP Computer Science A· difficulty 3/5

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

What is printed?

  • A

    0

  • B

    4

  • C

    -1

  • D

    3

    check_circle

Explanation

Linear search finds 4 at index 3. The loop continues but no other 4 exists, so idx stays at 3.

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

Related questions