All topics
4

Doing it for everyone: loops

Free

1. The problem

You deliver mail on a street with 40 mailboxes. Your task: put a flyer in each one. You don't write yourself 40 separate instructions. You repeat one thing: "go to the next mailbox, drop a flyer," until there are no mailboxes left.

Computers are built for exactly this kind of work. What they do best is repeat the same small step for a lot of items. They don't get tired, and they don't lose count at mailbox 37.

2. Repeat, for each item

A loop says: "for each box in the list, do this step." You write the step once. The computer runs it at every position, in order.

✉ ✉ ✉ ✉ same step, box after box

In words: "for each x in the list: drop a flyer." Here x is the name of the current box, the one the loop has reached. Four boxes, four flyers, one written instruction.

3. The counter

Often the loop keeps a small number that says where it is: 0, then 1, then 2, and so on. This counter is a variable too, a labeled box. It goes up by one each time around. From the counter the loop knows which position it is on and when to stop. Remember from the lesson on lists: the last position is one less than the length. For a list of 4 boxes the counter goes 0, 1, 2, 3. When it reaches 4, which is the length of the list, the boxes have run out and the loop stops.

4. Your turn (no code)

A loop walks through [4, 1, 7] and keeps a box called total. At the start it holds 0. Each time, the loop adds the current number to total. What is in total at the end?

Answer: 12. Step by step: at the start 0, after the first number 0 + 4 = 4, after the second 4 + 1 = 5, after the third 5 + 7 = 12. A loop plus one running-total box is enough to add up a whole list. You will write this shape all the time.

5. Takeaway

A loop does one step for every item, in order, and keeps track of its place with a counter. You write the step once, and the computer repeats it even a million times. This is the most common idea in all of programming.

On LeetCode

No code yet, so nothing to submit. The loop with a running total from this lesson is the whole of Running Sum of 1d Array and Richest Customer Wealth, and you write loops in code from lesson 7 on.

Reading as a guest

Every free lesson is open to read and run. A free account marks lessons done and shows where you are in the course.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy