Traversing a List to Build a Result
Looping over every item in a collection while carrying a running result: a total, a count, or the largest value seen so far.
Ce que l'enfant saura faire ensuite
- Total the numbers in a list with a loop and a running variable
- Count how many items match a condition
- Find the largest value without a built-in function, and justify the starting value
1 · Lis
To total a list you walk it once and carry a running total. Start the total at 0, then add each item in turn. For 6, 1, 5 and 3 the total grows 6, 7, 12 and lands on 15.
Counting matches works the same way with a counter starting at 0. In 4, 17, 9, 30 and 11, only 17, 30 and 11 pass the over-10 test, so the counter lands on 3.
To find the largest, carry the best seen so far and start it at the first item. In 21, 8, 34, 34 and 5 the best ends at 34. Starting at 0 would lie on an all-negative list like -6, -1, -12, since 0 beats them all yet sits in no slot.
Off-by-one slips lurk at the ends, so always test the first item, the last item and the empty list.
Walk every item once while a running total, counter or best-so-far carries your answer forward.
The rewritten readings were written for this dataset. Practice items adapted from WeBWorK Open Problem Library problems by Jason Terry (Louisiana Tech) (CC BY-NC-SA 3.0).
2 · Regarde
En anglaisSans écran
Où se situe ce sujet
À apprendre avant
18 questions attendent derrière cette leçon, chacune avec sa réponse expliquée. Chaque réponse nourrit le ciel : les étoiles s'allument à mesure qu'elles sont apprises, et pâlissent quand vient le moment de revenir.