In this tutorial we will provide additional examples of loop algorithms that process lists of data.
Recall the MakeList procedure, which uses a while loop to create a list of random numbers:
To MakeList do:
Set global theList to make-an-empty-list
While length(theList) < listSize do:
add a random number between 0 and 9 inclusive to theList
Each time the 'do' slot is executed, a random integer between 0 and 9 is added to thelist. Each time through the loop, the list will grow in size until it reaches a length of size at which point the test will be false and the loop will terminate.
As shown in this figure a correct while-loop statement must be combined with initialization steps and must contain update steps.
Initialization Step: Before we enter a while loop we need to perform some initializations. In this case we initialize theList to the empty list. And the listSize argument is also initialized to the value given when the procedure is called.
Loop Entry Condition: Before the while loop performs the do slot, it must test that the loop-entry-condition is true.
Update Step: At least one operation in the do slot must make progress toward the termination of the loop -- e.g., increasing the size of the list.
Question: What would happen if we didn't make progress toward termination? Question: What would happen if the test never became false? Watson: What is an infinite loop?
When dealing with lists, App Inventor provides a for-each loop that will perform some operation for each element on the list.
There are three slots that need to be filled in to define a for-each loop:
For example, suppose we want to compute the sum of the numbers on our random list. Let's write a Pseudocode function to do that, using the idea of for-each-item-in-a-list:
# Function using a for-each loop to compute the sum of a list of numbers.
# In this case the variable is named item
# In this case the in list is named aList
To computeListSum(aList) :
Set global Sum to 0
For each item is aList do:
Set Sum to Sum + item
Return Sum
And here is the App Inventor definition.
Let's use App Inventor's Watch and DoIt features to test our definition:
Question: Would you say that the for-each loop structure is an abstraction? Why or why not?
Working in pairs, perform each of the following exercises. If you do not finish in class, do the exercises for homework. HINT: Some of the operations required for these exercises use built-in functions that can be found in the App Inventor Lists and Text menus.