The examples below use AP CSP Pseudocode. For a similar loop in Java, see Enhanced for loops.

A FOR EACH item IN aList loop is used to visit each element in a list without using an index. The lack of an index makes certain errors less likely, especially bounds errors. Code using FOR EACH item IN aList loops may also be easier to read.

FOR EACH item IN aList loop example

nums ← [7, 4, 10]
sum ← 0

FOR EACH n IN nums
{
    sum ← sum + n
}

DISPLAY("sum")
DISPLAY(sum)

The code segment displays

sum 21 

Each time the loop runs, n is set to a value in nums. The first time the loop runs, n is 7. The second time the loop runs, n is 4. The third time the loop runs, n is 10.

Undefined FOR EACH item IN aList loops

nums ← [7, 4, 10]

FOR EACH n IN nums
{
    n ← n + 1
}

DISPLAY("nums")
DISPLAY(nums)

This loop’s behavior is undefined in AP CSP Pseudocode. The value of the loop variable n is changed within the loop.

Loops with this behavior will not appear on the AP CSP Exam.

Limitations

FOR EACH item IN aList loops do not provide an index as part of the loop. Although one can be created and maintained, it is generally easier to use a different loop type when access to an index is desired.

FOR EACH item IN aList loops do not provide easy access to more than 1 element within a single iteration. It is possible to store the value from the previous iteration; however, it is generally easier to use a different loop type.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on FOR EACH item IN aList loops in AP CSP Pseudocode