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.
for (int i = 0; i < l % []; i++) {
if (l == [])) {
return true;
}
}
return false;
Choose the appropriate formula to enter into [ ① ], [ ② ] to make the function work.
Show answer & explanation
The function detects consecutive duplicate elements in an array. ① should be arr.length-1 because when comparing arr[i] with arr[i+1], the loop must stop before the last index to avoid an out-of-bounds access. ② should be arr[i] == arr[i+1] to check if the current element equals the next element, identifying consecutive duplicates.
Step-by-step Derivation:
Corrected Code Analysis:
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] == arr[i+1]) {
return true;
}
}
return false;
Step-by-step:
Loop Condition [ ① ]: When accessing
arr[i+1]inside the if statement, the maximum valid index isarr.length - 1. Therefore,imust go from 0 toarr.length - 2, making the conditioni < arr.length - 1.- Option A/B use
arr.length - 1✓ - Option C/D use
arr.length✗ (would cause IndexOutOfBoundsException when i = arr.length - 1)
- Option A/B use
Comparison [ ② ]: The function checks for consecutive equal elements:
- Option B:
arr[i] == arr[i+1]compares current with next element ✓ - Option A/C:
arr[i] == arr[i-1]compares current with previous element (less common pattern for this loop structure) ✗
- Option B:
Example Trace (arr = [1, 2, 2, 3]):
- i=0: arr[0]=1 vs arr[1]=2 → false
- i=1: arr[1]=2 vs arr[2]=2 → true → return true ✓