| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice Test
Share
medium Solved by 11 students
Debugging a Java Array Search Loop
< Prev
Next >

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

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1kaisuki11 0m 00s 100
#2mullameh00112 2m 00s -30
#3singhris00011 3m 01s -81
#4aditirajaraman1027200811 3m 02s -82
#5geethasailaja12 4m 19s -169
#6ponneban00012 5m 19s -229
#7y.seong202713 9m 22s -482
APFIVE © 2020.
Email: [email protected]|Privacy Policy