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 containConsecutive(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 check consecutive elements, we need to compare each element with its next neighbor (arr[i] with arr[i+1]). The loop must iterate only up to arr.length-1 to avoid an index-out-of-bounds error when accessing arr[i+1] on the last iteration. Option C correctly uses both conditions: looping to arr.length-1 and comparing arr[i] == arr[i+1].
Step-by-step Derivation:
Analysis of each option:
Option A: arr.length-1, arr[i] == arr[i-1]
- Loop limit is correct (arr.length-1 prevents out-of-bounds)
- But compares current element with previous element
- For arr = {0, 3, 2, 2, 6, -1, 3}: when i=3, arr[3]=2, arr[2]=2, this would match but logic is backwards from typical left-to-right iteration
Option B: arr.length, arr[i] == arr[i+1]
- Loop limit is WRONG (i goes 0 to arr.length, so i+1 goes 1 to arr.length, causing index out of bounds)
- When i = arr.length-1, arr[i+1] would be arr[arr.length], which is invalid
Option C: arr.length-1, arr[i] == arr[i+1]
- Loop limit is CORRECT (i goes 0 to arr.length-2, so i+1 goes 1 to arr.length-1, all valid)
- Comparison is CORRECT (checks if current element equals next element)
- Trace for arr = {0, 3, 2, 2, 6, -1, 3}: i=2: arr[2]=2, arr[3]=2 → true ✓
Option D: arr.length, arr[i] == arr[i-1]
- Loop limit is WRONG (causes out-of-bounds when accessing arr[i+1] implicitly or arr[i-1] when i=0 could be problematic in context)
- When i=0, arr[i-1] = arr[-1] is invalid
Correct Answer: C