Choosing how to earn college credit? CLEP vs AP guide
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Data Collections
Start Practice TestPractice Test
About Exam
easy

Linear Search for Last Occurrence

Mark
< Prev
Next >

The findFirst method, shown below, performs a linear search to find the first occurrence of a target value in an integer array.

public static int findFirst(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}

Which of the following code segments, when used as the body of a method, correctly finds the index of the last occurrence of target in arr? If target is not found, the method should return -1.

A

int lastIndex = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { lastIndex = arr.length - 1; } } return lastIndex;

B

for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return arr.length - 1 - i; } } return -1;

C

for (int i = arr.length - 1; i >= 0; i–) { if (arr[i] == target) { return i; } } return -1;

D

for (int i = arr.length; i > 0; i–) { if (arr[i] == target) { return i; } } return -1;

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: apfive@apfive.org|Instagram: @_apfive_|Privacy Policy|