?

AP® Computer Science Principles

Free Version

Upgrade subject to access all content

Moderate

Replacing a For Each Loop

APCSP-8EG4GY

Use the following code segment to answer this question:

x ← 8
answer ← - 1
aList ← [1, 4, 7, 9, 11, 14]
FOR EACH item IN aList
{
    IF (item = x)
    { answer ← item }
}

Which of the following code segments could replace the FOR EACH loop above without changing the outcome of the code?

A
FOR EACH item IN aList
{
    IF (item = x)
    { answer ← item }
    ELSE
    { answer ← -1 }
}
B
len ← LENGTH (aList)
i ← 1;
REPEAT len TIMES
{
    IF (aList[i] = x)
    { answer ← x }
    ELSE
    { answer ← -1 }
    i ← i + 1
}
C
len ← LENGTH (aList)
i ← 1;
REPEAT len TIMES
{
    IF (aList[i] = x)
    { answer ← x }
    i ← i + 1
}
D
len ← LENGTH (aList)
i ← 1;
REPEAT len TIMES
{
    IF (aList[i] = x)
    { answer ← x }
}
i ← i + 1