This Java function receives an input of array of integers arr and outputs true if there are...
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
This Java function receives an input of array of integers arr and outputs true if there are any neighboring array elements that have the same value in the array.
For example:
- Given
arr = {0, 3, 2, 2, 6, -1, 3}, the elements2, 2are next to each other and are the same value, sotrueis returned. - Given
arr = {0, 3, 2, 5, 6, -1, 3}, there are no elements with the same values next to each other, sofalseis returned.
static boolean containsConsecutive(int[] arr) {
for (int i = 0; i < ① ; i++) {
if ([ ② ]) {
return true;
}
}
return false;
}
Choose the appropriate formula to enter into [ ① ], [ ② ] to make the function work.
Show answer & explanation
To detect consecutive equal elements, we need to compare each element with its next neighbor. The loop must iterate only to arr.length-1 because at that point we compare arr[i] with arr[i+1], and accessing arr[arr.length] would cause an ArrayIndexOutOfBoundsException. Option B correctly uses arr[i] == arr[i+1] to check consecutive pairs.
Step-by-step Derivation:
Step-by-step analysis:
Loop bound (①): If we iterate to
arr.length, the conditionarr[i] == arr[i+1]wheni = arr.length-1would accessarr[arr.length], which is out of bounds. So we must usearr.length-1.Comparison condition (②): We need to compare consecutive elements. Starting from
i=0, we comparearr[i]witharr[i+1]. This checks each pair: (arr[0], arr[1]), (arr[1], arr[2]), ..., (arr[arr.length-2], arr[arr.length-1]).Verification with example 1:
arr = {0, 3, 2, 2, 6, -1, 3}- i=0: arr[0]==arr[1]? (0==3) → false
- i=1: arr[1]==arr[2]? (3==2) → false
- i=2: arr[2]==arr[3]? (2==2) → true ✓ (returns true)
Verification with example 2:
arr = {0, 3, 2, 5, 6, -1, 3}- Loop completes without finding equal consecutive elements → returns false ✓
Why other options fail:
- Option A:
arr[i] == arr[i-1]when i=0 accesses arr[-1], causing an error. - Option C:
arr.lengthallows i=arr.length-1, makingarr[i+1]access arr[arr.length], out of bounds. - Option D: Same issue as C—loop goes too far.
- Option A: