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

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

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1kaisuki11 0m 00s 100
#22023167911 0m 05s 95
#3mullameh00112 2m 00s -30
#4singhris00011 3m 01s -81
#5aditirajaraman1027200811 3m 02s -82
#6geethasailaja12 4m 19s -169
#7ponneban00012 5m 19s -229
#8y.seong202713 9m 22s -482
#9chunxiangxu.cxu01 10m 38s -648
Items per page:
10
1 – 9 of 9
No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy