(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

while test { }
do { }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.  

while test condition code block: 
while test { get counter ≤  get userinput} 
do { }

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. Click answer to self-check.

code block in scratch:
when
Button1.Click
do
initialize local counter to 0
initialize local sum to 0
in
while test get counter ≤ get userInput
do
set sum to 0 get counter + get sum
set counter to 0 get counter + 1
set Label1 Text to get sum

code block in Java:
public class GetSum
public static void main (String[] args)
{
int sun = 0;
int counter = 0;
int userinput = 4;
while (counter <= userinput)
{
sum = sum + counter:
counter counter + 1;
}
System.out.println(sun);
}
}

 

Answer

foreach

screenshot of app screen:
Screen 1
click for contents of list
clear
20 14 75 4The 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.    

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