19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Associative Arrays<br />

In the previous chapter, you learned how <strong>to</strong> use an integer index <strong>to</strong> access<br />

an array’s elements. But in <strong>Small</strong> <strong>Basic</strong>, an array’s index can also be a string.<br />

Arrays indexed by strings are called associative arrays, maps, or dictionaries.<br />

In this book, we’ll call them associative arrays. Just like an indexed array,<br />

an associative array can s<strong>to</strong>re values of any type. You can use an associative<br />

array <strong>to</strong> create an association between a set of keys (string indices) and a set<br />

of values, which is called creating a map of key-value pairs.<br />

The following code shows a simple example of an associative array in<br />

action. It’s a list of states keyed by their two-letter abbreviations:<br />

state["CA"] = "California"<br />

state["MI"] = "Michigan"<br />

state["OH"] = "Ohio"<br />

' ... and so on<br />

To display the name of a state, you simply use its corresponding key<br />

and the proper syntax. For example, <strong>to</strong> display Michigan, you can write this<br />

statement:<br />

TextWindow.WriteLine(state["MI"])<br />

By writing the name of the array followed by the key enclosed in square<br />

brackets, you can access the corresponding item. An associative array works<br />

like a lookup table that maps keys <strong>to</strong> values; if you know the key, you can find<br />

its value very quickly.<br />

To learn how <strong>to</strong> use associative arrays, let’s write a program that keeps<br />

track of the ages of your friends by name. Enter the program in Listing 16-1.<br />

1 ' AssociativeArray.sb<br />

2 age["Bert"] = 17<br />

3 age["Ernie"] = 16<br />

4 age["Zoe"] = 16<br />

5 age["Elmo"] = 17<br />

6 TextWindow.Write("Enter the name of your friend: ")<br />

7 name = TextWindow.Read()<br />

8 TextWindow.Write(name + " is [")<br />

9 TextWindow.WriteLine(age[name] + "] years old.")<br />

Listing 16-1: Using associative arrays<br />

Lines 2–5 create an associative array named age <strong>with</strong> four elements in<br />

it. You can add more if you’d like, or you can change the array <strong>to</strong> s<strong>to</strong>re the<br />

ages of your own friends. Line 6 asks you <strong>to</strong> enter a friend’s name, and line<br />

7 reads it in<strong>to</strong> the name variable. In line 9, age[name] looks up the age of that<br />

friend.<br />

228 Chapter 16

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!