Lesson 16. Repeating tasks with loops

 

After reading lesson 16, you’ll be able to

  • Understand what it means for a line of code to repeat execution
  • Write a loop in a program
  • Repeat actions a certain number of times

The programs you’ve seen so far have statements that are executed once, at most. In the preceding unit, you learned to add decision points in your programs, which can break up the flow by making the program react to input. The decision points are governed by conditional statements that may cause your program to take a detour to execute other lines of code if a certain condition holds.

These kinds of programs still have a type of linearity to them; statements are executed top to bottom, and a statement can be executed either zero times or at most one time. Therefore, the maximum number of statements that can be executed in your program is the maximum number of lines in the program.

Consider this

It’s a new year, and your resolution is to do 10 push-ups and 20 sit-ups every day. Look at the following flowchart to determine the number of sit-ups and push-ups you’ll do in one year.

A flowchart illustrating how you can repeat certain tasks. Sit-ups are repeated 10 times, and push-ups are repeated 20 times. Both sit-ups and push-up sequences are done every day of the year

Answer: 3,650 sit-ups and 7,300 push-ups

16.1. Repeating a task

16.2. Looping a certain number of times

16.3. Looping N times

Summary

sitemap