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

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

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 uses a linear search that returns the 1-indexed position of the first occurrence of x, or -1 if not found. Option C is correct: when the loop completes without finding x, the function explicitly returns -1. Option A is false because an empty array simply causes the loop condition i < 0 to be false on the first iteration, returning -1 without error. Option B is false because the function returns immediately upon finding the first match, so only one occurrence is ever returned.

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

  1. If a is empty (length 0): Loop condition i < a.length evaluates to 0 < 0 = false. Loop skips. Function returns -1. No abnormal termination.
  2. If x has multiple matches: The return statement inside the if block terminates the function immediately when the first match is found at index i. Subsequent occurrences are never checked.
  3. If x is not found: The loop completes all iterations without entering the if block. After the loop ends, the function reaches return -1; and returns -1.

Therefore, only statement C is correct.