Debugging a Java Array Search Loop
The following code fragment is intended to search for a value target in arr[0] to arr[n-1] and set found to true if it is found, but it does not work 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;
}
For the segment to work as intended, which of the following modifications could be made?
I. Change the initialization int i = 0; to int i = -1; Make no other changes.
II. Change the loop condition to i < n - 1 && !found. Make no other changes.
III. Move the i++ statement to after the if statement in the loop body. Make no other changes.
A
I and III only
B
II only
C
I only
D
I and II only
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #2 | mullameh001 | 1 | 2 | 2m 00s | -30 |
| #3 | singhris000 | 1 | 1 | 3m 01s | -81 |
| #4 | aditirajaraman10272008 | 1 | 1 | 3m 02s | -82 |
| #5 | geethasailaja | 1 | 2 | 4m 19s | -169 |
| #6 | ponneban000 | 1 | 2 | 5m 19s | -229 |
| #7 | y.seong2027 | 1 | 3 | 9m 22s | -482 |
APFIVE