Sample lessons

Sample lesson · Computer Science

Teaching a computer to count and add up

What you will be able to do

By the end of this lesson you will be able to:

  • explain what an accumulator is and where its three parts go: before the loop, inside it and after it,
  • write a for loop that adds up the numbers in a list,
  • adapt the same loop to count the items that pass a test and to find the largest item,
  • spot the common mistakes that make an accumulator loop give the wrong answer.
Words used in this lesson (7)
accumulator
A variable that is updated on each pass of a loop, so that it carries a result such as a total from one item to the next.
initialise
To give a variable its first value. An accumulator is initialised once, before the loop starts.
update
To compute a new value from a variable's current value and store it back, as in total = total + price.
iteration
One pass through the body of a loop. A for loop over a list performs one iteration for each item.
loop body
The indented lines under a for statement, which run once for each item.
running total
The value of a total part-way through a loop: the sum of the items seen so far.
trace
To follow a program by hand, line by line, writing down the value of each variable as it changes.

In the academy, a lesson is one step of a path

In a program of your own, lessons like this one are arranged around your goal, your place and answers are kept, and a tutor is on hand to question your reasoning.