Chapter 20. Repeating Blocks: Iteration

image with no caption

One thing computers are good at is repeating operations—like little children, they never tire of repetition. They are also very fast and can do things like process your entire list of Facebook friends in a microsecond.

In this chapter, you’ll learn how to program repetition with just a few blocks instead of copying and pasting the same blocks over and over. You’ll learn how to do things like send an SMS text to every phone number in a list and sort list items. You’ll also learn that repeat blocks can significantly simplify an app.

Controlling an App’s Execution: Branching and Looping

In previous chapters, you learned that you define an app’s behavior with a set of event handlers: events and the functions that should be executed in response. You also learned that the response to an event is often not a linear sequence of functions and can contain blocks that are performed only under certain conditions.

Repeat blocks cause a program to loop
Figure 20-1. Repeat blocks cause a program to loop

Repeat blocks are the other way in which an app behaves nonlinearly. Just as if and ifelse blocks allow a program to branch, repeat blocks allow a program to loop; that is, to perform some set of functions and then jump back up in the code and do it again, as illustrated in Figure 20-1.

When an app executes, ...

Get App Inventor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.