(MAI) Iteration Lesson
Iteration
Iteration is another essential programming concept. Iteration is used to search through and manipulate list and repeat blocks of code.
There are two types of blocks for iteration in App Inventor:
while
A while loop will repeat any condition while it is true. It is a more general type of loop that can be used to iterate anything. The while-do blocks require a conditional test just like if statements.
A while loop has a test which is boolean expression that will evaluate to true or false.
Examine the code below. What does it do? On the left is the App Inventor code. On the right is the same code in Java.
foreach
The foreach block is used to process a list. It applies a set of functions to each element of the list. Analyze the code below. This code will print the contents of a list.
View a full transcript of the above image here.
code block:
initialize global number to
make a list 20 14 75
explanation: Create a global variable to store the list. Use the make a list block to create the list.
code block:
initialize global listContents to { }
explanation: Create a global variable and assign an empty string. This will be used to store the items in the list through each iteration of the loop.
code block:
when Button1.Click
do
for each item in list get global number
do
set global listContents to get item
set Label2 Text to
join Label2 Text
get global listContents
{ }
explanation: The event handler will be when Button1 is clicked.
get global listContents
The for each item in a list block requires the list to search through. Remember you must use the get block to get information from variables. The do block will get the items in the list and set them to the empty text variable through each iteration. The Label will display the contents of the variable.
code block:
when Button2.Click
do set Label2 Text to { }
explanation: Another button can be created to clear the contents of the label by setting the contents to an empty text block when clicked.
Searching for Numbers and Strings
The foreach is used to search through a list to find an element in the list. Go through the learning object to analyze the code for searching for a number and searching for a string.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION