The greenhouse team asks Beacon for one number: the average water reading for the day.
Comet starts typing readings[1] + readings[2] + readings[3]. She stops. "What if tomorrow has a different number of readings?"
Wren nods. "Then your line breaks. We need a way to visit every element, however many there are."
Comet tries readings[7] to see what happens. The paper test stops with an error.
"There is no seventh box," Wren says.
Nova circles the list on the board. "Let's investigate," she says.
"What if Beacon walked down the list, one box at a time, and kept a running total?"
On the AP reference sheet, list indexes run from 1 to the number of elements.
An index less than 1, or greater than the length of the list, produces an error, and the program ends.
Traversing a list means visiting its elements. A complete traversal visits all of them. A partial traversal visits only some.
FOR EACH item IN aList visits each element in order, from the first to the last.
On each pass, the variable item gets the value of the next element.
total ← 0
FOR EACH reading IN readings
{
total ← total + reading
}
average ← total / 6
DISPLAY(average) | Pass | reading | total |
|---|---|---|
| Start | (none yet) | 0 |
| 1 | 62 | 62 |
| 2 | 58 | 120 |
| 3 | 54 | 174 |
| 4 | 48 | ? |
| 5 | 70 | ? |
| 6 | 68 | ? |
| About FOR EACH | True or false? |
|---|---|
| FOR EACH visits the elements in order, from first to last. | ? |
| On each pass, the loop variable gets the next element's value. | ? |
| A complete traversal skips some elements. | ? |
| FOR EACH works the same way whether the list has 6 elements or 24. | ? |
You can also assign a new value to one element. The rest of the list stays the same.
In the line below, the element at index 2 gets 60.
readings[2] ← 60
Nice work. Tomorrow in Beacon Lab, index cards become a list you can hold in your hands.