OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

The following JavaScript function returns the number where the integer x occurs in the...

Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.

The following JavaScript function returns the number where the integer x occurs in the given array of integers a.

function find(a, x) {
  for (let i = 0; i < a.length; i++) {
    if (a[i] == x) {
      return i + 1;
    }
  }
  return -1;
}

Choose the correct statement regarding this function.

Choose one option.
Show answer & explanation
Answer: C. If x is not found in array a, the function returns -1.

The function iterates through array a and returns i+1 (the 1-based position) when x is found. If the loop completes without finding x, it returns -1. Option A is incorrect because an empty array causes the for loop condition to be false immediately, so no abnormal termination occurs. Option B is incorrect because the function returns immediately upon finding the first occurrence, not all occurrences.

Step-by-step Derivation:
Trace the function logic:

  1. If a = [] and x = 5: The loop condition i < 0 is false, so the loop never executes. The function reaches return -1 and exits normally.
  2. If a = [1, 2, 3, 2, 4] and x = 2: On iteration i=1, a[1]==2 is true, so the function returns 1+1=2 and exits. The second occurrence at i=3 is never checked.
  3. If a = [1, 3, 5] and x = 7: The loop completes all iterations without finding a match, and return -1 is executed.
    Therefore, statement C is correct.