LightMySky

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.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • 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 · Read

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 4, 7, 2 and 9 the total grows 4, 11, 13 and lands on 22.

Try it together

Counting matches works the same way with a counter starting at 0. In 3, 8, 15, 22, 6 and 19, only 15, 22 and 19 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 12, 45, 7, 39, 45 and 3 the best ends at 45. Starting at 0 would lie on an all-negative list like -8, -2, -15, -4, since 0 beats them all yet sits in no slot.

Good to know

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.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Traversing a List to Build a Result · Computing, ages 15 to 16 · LightMySky