Debugging a Java Array Search Loop
Consider the following code segment, which is intended to search for a target value within an integer array arr. The segment should set the boolean variable found to true if the target is present. However, the code 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 proposed modifications will cause the code segment to work as intended?
I. Change the initialization int i = 0; to int i = -1;.
II. Change the while loop condition to i < n - 1 && !found.
III. In the body of the while loop, move the i++; statement to be after the if statement.
A
I and III only
B
I and II only
C
II only
D
I only
APFIVE