Choose the appropriate formula to enter into [ ① ], [ ② ] to make the function work.
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
static boolean containConsecutive(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if ([ ① ]) {
return true;
}
}
return false;
}
Choose the appropriate formula to enter into [ ① ], [ ② ] to make the function work.
Show answer & explanation
The function iterates through the array checking consecutive pairs. The loop condition i < arr.length - 1 ensures we safely access arr[i+1]. To check if two consecutive elements are equal, we need arr[i] == arr[i+1], which returns true when a match is found. Other options either use incorrect comparisons or operations (!=, +=, <) that don't check for equality.
Step-by-step Derivation:
The function goal: return true if any two consecutive elements in the array are equal. Logic: (1) Loop from i=0 to i=arr.length-2 (safe to access arr[i+1]). (2) At each position, compare arr[i] with arr[i+1]. (3) If equal (arr[i] == arr[i+1]), immediately return true. (4) If loop completes without finding equals, return false. Therefore, [ ① ] = arr[i] == arr[i+1].