| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Java Array Search Loop Logic
< Prev
Next >

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

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

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy