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
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #2 | 20231679 | 1 | 1 | 0m 05s | 95 |
| #3 | mullameh001 | 1 | 2 | 2m 00s | -30 |
| #4 | singhris000 | 1 | 1 | 3m 01s | -81 |
| #5 | aditirajaraman10272008 | 1 | 1 | 3m 02s | -82 |
| #6 | geethasailaja | 1 | 2 | 4m 19s | -169 |
| #7 | ponneban000 | 1 | 2 | 5m 19s | -229 |
| #8 | y.seong2027 | 1 | 3 | 9m 22s | -482 |
| #9 | chunxiangxu.cxu | 0 | 1 | 10m 38s | -648 |
Items per page:
10
1 – 9 of 9
APFIVE