A traversal visits the elements of a list one at a time: a complete traversal visits every element, and a partial traversal visits only some. In AP® Computer Science Principles you traverse with FOR EACH, which hands you each element in order, or with an index variable that counts from 1 to LENGTH(aList). A traversal lets one short loop sum, count, find a maximum or minimum, filter or search a list of any size.
Quick check
For tools ← [4, 9, 2], what is tools[LENGTH(tools)]?Show answerHide answer
LENGTH(tools)is 3, and the element at index 3 is 2.
How many times does the body of REPEAT LENGTH(tools) TIMES run when tools has 3 elements?Show answerHide answer
3 times, once for each element.
A FOR EACH loop and an index loop both visit every element of a list. Which one also tells you each element's position?Show answerHide answer
The index loop: its variable
iis the position, andaList[i]is the element there.
Know these already? Jump to the practice questions
What you'll be able to do
- Predict what a
FOR EACHor index traversal displays. - Choose between
FOR EACHand an index loop for a task. - Use a traversal to sum, count, find a maximum or minimum, filter or search.
- Explain how a list manages complexity compared with separate variables.
Key terms
Traversal
Visiting the elements of a list one at a time. A complete traversal visits every element; a partial traversal visits only some.
- In plain English
- Walking along the list and looking in the boxes.
- Don't write
- "A traversal sorts the list."
Filter
Building a new list that holds only the elements that meet a condition.
- In plain English
- Keeping the items that pass a test.
- Don't write
- "A filter deletes elements from the original list."
Data abstraction
Treating many related values as one named thing, such as a list, so code can handle them together without naming each value.
- In plain English
- One label for many values.
- Don't write
- "A list is useful because it uses less memory."
How does FOR EACH traverse a list?
FOR EACH item IN aList sets item to the first element, runs the block, then sets it to the second, and so on to the last. That makes it a complete traversal. It is on the exam reference sheet.
prices ← [4, 9, 2, 5]
total ← 0
FOR EACH p IN prices
{
total ← total + p
}
DISPLAY(total)
p takes the values 4, 9, 2 and 5, so total goes 4, 13, 15, 20 and the segment displays 20.
p holds a copy of each value, not its position. So FOR EACH suits jobs that only read values: sums, counts, maximums and filters.
Check yourself
Show answerHide answer
4 times, once per element, and p is 5 on the last pass.
How do you traverse with an index?
An index loop uses a variable i as the position. It starts at 1 and goes up by 1 each pass.
v ← [3, 8, 1, 6]
i ← 1
REPEAT LENGTH(v) TIMES
{
v[i] ← v[i] * 2
i ← i + 1
}
After the loop, v is [6, 16, 2, 12]. Use an index when you need the position, when you change elements in place, or for a partial traversal: start i elsewhere, add 2 each pass, or stop early with REPEAT UNTIL(i > LENGTH(v)) plus an extra condition.
Key idea
An index loop covers indexes 1 to LENGTH(aList); it is complete only if i reaches the last index.
Check yourself
Show answerHide answer
Indexes 2, 4 and 6, so it is a partial traversal.
Which algorithms run on a traversal?
Each one sets up before the loop, does one job per element, and gives its answer after.
| Algorithm | Before | For each element x |
|---|---|---|
| Sum | total ← 0 | total ← total + x |
| Count | count ← 0 | if x meets the condition, add 1 to count |
| Maximum | big ← aList[1] | if x > big, set big to x |
| Minimum | small ← aList[1] | if x < small, set small to x |
| Filter | keep ← [] | if x meets the condition, APPEND(keep, x) |
| Search | found ← false | if x is the target, set found to true |
These patterns are Learn this. Searching, and how many elements a search checks, is the subject of the note on linear search and binary search.
Check yourself
Show answerHide answer
[4, 10, 8]. Each even element is appended in the order it is visited.
How does a list manage complexity?
Picture 30 quiz scores in 30 variables, score1 to score30. Adding them takes a 30-term expression, and a 31st score means new code. In a list, one name stands for every score, and one traversal handles any number of them: the code that sums 3 scores also sums 3,000.
That is data abstraction: you work with the collection as one thing and ignore how many values it holds. Your Create program must use a list that helps manage complexity, so be ready to explain how yours does this.
Check yourself
Show answerHide answer
It runs once per element, using FOR EACH or LENGTH(aList), so it adapts to any length.
Worked example 1: Trace a maximum and a count
Question: What is displayed when this code segment runs?
temps ← [18, 25, 21, 25, 19]
high ← temps[1]
count ← 0
FOR EACH t IN temps
{
IF(t > high)
{
high ← t
}
IF(t > 20)
{
count ← count + 1
}
}
DISPLAY(high)
DISPLAY(count)
What tells you the method
Two variables change inside a FOR EACH, so trace with one row per element.
Step 1: Trace each pass.
thighcount18 18 0 25 25 1 21 25 2 25 25 3 19 25 3 WhyThe two
IFblocks are separate, so each is tested on every pass.Step 2: Read the displays.
25, then 3, on one line.
WhyEach
DISPLAYshows its value followed by a space.
Check it
The values above 20 are 25, 21 and 25: three of them. The second 25 does not change high, because 25 > 25 is false.
Answer
25 3
Worked example 2: Design a filter
Question: prices ← [12, 4, 9, 15, 7]. Design code that builds a list cheap of the prices under 10, then state what DISPLAY(LENGTH(cheap)) followed by DISPLAY(cheap[1]) shows.
What tells you the method
A design task: input, output, steps, then a trace to test.
Step 1: State the input, output and plan.
Input:
prices. Output: a new list of the prices below 10. Plan: start with an empty list and append each price that passes.WhyA filter builds a new list, so the original stays unchanged.
Step 2: Write the steps.
cheap ← [] FOR EACH p IN prices { IF(p < 10) { APPEND(cheap, p) } }WhyOnly the values matter, not their positions, so
FOR EACHfits.Step 3: Trace it.
12 fails; 4 passes; 9 passes; 15 fails; 7 passes.
cheapis [4, 9, 7].WhyElements are appended in the order visited.
Check it
Two prices failed and three passed: 2 + 3 = 5, the length of prices. The displays show 3 and 4.
Answer
3 4
Worked example 3: A partial traversal
Question: What is displayed when this code segment runs?
vals ← [5, 2, 8, 1, 6, 3]
i ← 1
total ← 0
REPEAT UNTIL(i > LENGTH(vals))
{
total ← total + vals[i]
i ← i + 2
}
DISPLAY(total)
- A) 6
- B) 13
- C) 19
- D) 25
What tells you the method
The index goes up by 2, so list the indexes it visits.
Step 1: List the indexes.
iis 1, 3, 5, then 7, which is greater than 6, so the loop stops.WhyThe condition is checked before each pass.
Step 2: Add those elements.
vals[1] + vals[3] + vals[5]= 5 + 8 + 6 = 19.WhyOnly the odd indexes are visited.
Check it
The last pass reads index 5; then i becomes 7, past the length 6, so no index beyond the list is ever read.
Answer
C
Your turn
Question: What is displayed when this code segment runs?
names ← ["Ava", "Ben", "Cy", "Ben"]
pos ← 0
i ← 1
REPEAT LENGTH(names) TIMES
{
IF(names[i] = "Ben")
{
pos ← i
}
i ← i + 1
}
DISPLAY(pos)
Step 1: Passes 1 and 2.
"Ava" is not "Ben"; then
names[2]is "Ben", soposis 2.Step 2: Your go: trace passes 3 and 4.
Show the full solutionHide the solution
Step 2. Pass 3: "Cy" is not "Ben". Pass 4: names[4] is "Ben", so pos becomes 4. The loop does not stop at the first match, so it reports the last one.
Answer: 4
Traps
Trap
Changing item inside FOR EACH changes the list.
It seems right because item holds the element's value. But item is a separate variable given a copy of each value, so the list is unchanged. To change elements, use an index: aList[i] ← ….
a ← [1, 2, 3], then FOR EACH x IN a { x ← x * 10 }. What does a hold?
[1, 2, 3], unchanged.
Trap
You can REMOVE during an index traversal and still visit everything.
It seems right because i still goes up by 1. But after REMOVE(aList, i), the next element slides down into index i, and i ← i + 1 skips it.
Removing negatives from [3, -1, -4, 5] with REMOVE inside the IF and i ← i + 1 on every pass leaves what?
[3, -4, 5]. The -4 slid into index 2 and was skipped.
Trap
REPEAT UNTIL(i = LENGTH(aList)) reaches the last element.
It seems right because the last index is LENGTH(aList). But the loop stops as soon as i equals it, before that pass runs. Use REPEAT UNTIL(i > LENGTH(aList)).
With i starting at 1 and going up by 1, does REPEAT UNTIL(i = 4) process index 4?
No. It processes indexes 1, 2 and 3, then stops.
What's examined
On the AP® Computer Science Principles exam, traversals belong to Big Idea 3: Algorithms and Programming. Multiple-choice questions ask what a traversal displays, which code completes a list algorithm, and what a list holds afterwards. Your Create program must use a list that manages complexity, and the written-response questions ask about your own program.
Practice questions
- Recall Why does storing 30 scores in one list manage complexity better than 30 separate variables?
- A) One traversal can process every score, and the same code works if the number of scores changes.
- B) A list always uses less memory than separate variables.
- C) A list keeps its values sorted automatically.
- D) A list prevents index errors.
Show answer
Answer: A. One name and one loop handle the whole collection, whatever its size.
Why the others are wrong:
- B confuses managing complexity with saving memory.
- C is false: a list keeps the order you give it.
- D is false: an index outside 1 to
LENGTHis still an error.
- Apply What is displayed when this code segment runs?
s ← [6, 11, 3, 14, 8]
total ← 0
n ← 0
FOR EACH x IN s
{
IF(x > 5)
{
total ← total + x
n ← n + 1
}
}
DISPLAY(total)
DISPLAY(n)
Show answer
Answer: 39 4
Marking points:
- 6, 11, 14 and 8 are greater than 5; 3 is not.
- 6 + 11 + 14 + 8 = 39, and 4 values passed.
- Apply After this code segment runs, what are (a)
lowand (b)where?
d ← [9, 4, 12, 4, 7]
low ← d[1]
where ← 1
i ← 2
REPEAT UNTIL(i > LENGTH(d))
{
IF(d[i] < low)
{
low ← d[i]
where ← i
}
i ← i + 1
}
Show answer
Answer: (a) 4 (b) 2
Marking points:
- At index 2, 4 < 9, so
lowis 4 andwhereis 2. - At index 4, 4 < 4 is false, so the tie does not move
where.
- Exam-style The code should display the largest element of
nums. Give the number of the line that stops it working.
1: nums ← [4, 11, 7, 15]
2: big ← nums[1]
3: i ← 2
4: REPEAT UNTIL(i = LENGTH(nums))
5: {
6: IF(nums[i] > big)
7: {
8: big ← nums[i]
9: }
10: i ← i + 1
11: }
12: DISPLAY(big)
Show answer
Answer: Line 4.
Marking points:
- The loop stops when
iis 4, sonums[4], which is 15, is never checked, and 11 is displayed. REPEAT UNTIL(i > LENGTH(nums))makes it display 15.
- Exam-style What does
whold after this code segment runs?
w ← [2, -3, -5, -1, 6]
i ← 1
REPEAT UNTIL(i > LENGTH(w))
{
IF(w[i] < 0)
{
REMOVE(w, i)
}
i ← i + 1
}
- A) [2, 6]
- B) [2, -5, 6]
- C) [2, -5, -1, 6]
- D) An error, because
ipasses the end of the list
Show answer
Answer: B. Removing -3 slides -5 into index 2, which is skipped; at index 3, -1 is removed; then i is 4, past the new length of 3.
Why the others are wrong:
- A is what the code was meant to do, ignoring the skipped element.
- C assumes the loop stops after the first removal.
- D ignores that
LENGTH(w)is checked again before each pass, sow[i]is never read past the end.
- Exam-style
nums ← [5, 10, 15, 20, 25]andbig ← []. Which line can replace<MISSING CODE>sobigends up holding every element that is at least 15?
FOR EACH n IN nums
{
<MISSING CODE>
}
- A)
IF(n > 15) { APPEND(big, n) } - B)
IF(n ≥ 15) { big ← n } - C)
IF(n ≥ 15) { APPEND(nums, n) } - D)
IF(n ≥ 15) { APPEND(big, n) }
Show answer
Answer: D. It appends 15, 20 and 25 to big.
Why the others are wrong:
- A misses the boundary value 15.
- B replaces the list with a single number instead of adding to it.
- C appends to the wrong list, so
bigstays empty.
- Recall Name the loop on the exam reference sheet that sets a variable to each element of a list in turn, from first to last.
Show answer
Answer: FOR EACH
Marking points:
FOR EACH item IN aListgivesitemeach element in order.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
FOR EACHreads every value in order; an index loop also gives you the position.- Change elements through
aList[i], never through theFOR EACHvariable. - A partial traversal starts late, steps by more than 1 or stops early.
- Sum, count, maximum, minimum, filter and search all set up before the loop and do one job per element.
- A list plus a traversal handles any amount of data with the same code.