Java Array Search Loop Logic
The following code segment is intended to search an integer array arr for a target value. The boolean found should be set to true if the target is present; otherwise, it should remain false. However, the code contains an error and does not function as intended.
/** Precondition:
* - arr is an array of integers, arr.length = n.
* - target is the value to search for.
* Postcondition: found == true if target is in arr[0..n-1]; false otherwise. */
boolean found = false;
int i = 0;
while (i < n && !found) {
i++;
if (arr[i] == target)
found = true;
}
Which of the following modifications would correct the error in the code segment?
I. Change the statement int i = 0; to int i = -1;.
II. Change the while loop’s condition to i < n - 1 && !found.
III. Move the i++; statement to be after the if statement within the loop.
A
II only
B
I and III only
C
I only
D
I and II only
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE