Loops – Overview

By the time students see loop constructs, they have an understanding of the use of variables and the flow of execution of code. The typical loop constructs are while and for loops (they correspond to repeat until and repeat in Scratch). Some insights:

  • Loops are a great opportunity to clarify remaining misconceptions about the use of variables and the flow of execution.
  • Difficulties with tracing and writing loops are often tied to misconception and earlier topics not yet fully mastered.

We all execute some daily tasks in a repeating matter. Sometimes actions are repeated for a fixed number, other times until a specified event happens. Here are some examples:

  • Your favorite coffee house has a rewards card which gives you one free coffee after you have bought 10. For the car wash, it takes 15 car washes to get a free one. In either case, one repeats an action a fixed number of times before getting a reward.
  • Your favorite outdoor store gives a $25 rebate after you have bought $500 worth of goods. How long it takes one to spend $500 will vary. It is at least one purchase. How many purchases depends on how much one spends over time.
  • You practice for the upcoming piano recital. The daily routine you choose is to repeat the piece until you play it flawlessly for 3 times in a row or you have practiced for 2 hours.
  • Cycling through all the people who sent you a graduation present and sending a thank you note. One may do some preprocessing so that the notes are sent out in batches and different priorities are met.
  • You set a reminder on your smartphone for a particular time with a fixed repetition. You may choose a “forever” setting; e.g., have the alarm ring every weekday at 6:30am.

Students should come up with other examples of iterations of either type: a fixed number of iterations or iterating until a specified event happens. For any repeating situation translating into loops there will be quantities that one needs to keep track of (they correspond to the variables a program will need to store).

Project PD4CS prepared four main sections on loops. They include:

All the programs are available in this post: