Lesson Plan: Iterate through a list

This lesson provides a crucial leap into the world of abstract programming through discussion/demonstration of apps that sequence through a list of information (specifically when the user clicks a button to go to the next item).

The lesson starts with a concrete solution: if-else-else... is used to sequence, with the items being sequenced concretely in the code. Discussion then centers on the inflexibility of this solution, i.e. what if the list of items is not static but user-generated and dynamic. A more abstract solution, based on a list and an index, is then presented and discussed.

1. Discussion question: How would you build a slide show of images. When the user clicks on the image, it should change to the next in the list.

2. There are two strategies:
  • The if-else solution: On the click event, you have an if-else-else.. which chooses which image to show next.
  • Using a list and walking through the list using an index variable. This is a more flexible solution that will work on any list even if the list changes.

3. Demonstrate the if-else solution
  • upload three images
  • set Button.BackgroundImage to first image in designer
  • In blocks editor, use if-else-else to sequence through images. Go back to first image after last.
    • Note how file name of loaded image is used and must be set exactly.
4. Discuss if-else

How would you add another item (image) to the app?
(add an else clause)
What if the images were user-generated, e.g., rifling through flickr pics?
(scheme doesn't work-- you have to modify program)

5. Discuss Alternative solution using a list and an index variable

List-- a single variable (name) that represents a set of data. Like variables you've seen the data is not visible unless you put in label.
Index -- a number variable that represents a position in a list variable. 1 is first, 2 is second, etc.
select item from list block
incrementing index
set index to index + 1

Draw list on whiteboard with data (image names) in it. Show a memory cell for index, and how it changes with

set index to index + 1
filename= select item from list (imagelist,index)

6. Re-build image sequencer using a list and index.
  • first not worrying about last item, then show bomb out
  • add if statement at end that sets index back to 1. On first solution, use if index>3
  • introduce length of list and fix so that "if index < length of list"
7. Discussion

How to add another item (image)? Just add to list, don't change code
What if items are added to list dynamically (user-generated)?
No problem, code blocks work on any list

Abstraction-- we are leaving the world of concreteness. Now our code works on an any list of any size, but the code is more abstract. Get used to it!

8. Activity: Quiz tutorial (either President's Quiz from book (ch 8) or on-line baseball quiz

© AppInventor.org 2012