06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

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

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

144 <strong>Learning</strong> <strong>Processing</strong><br />

9.2<br />

What is an array?<br />

From Chapter 4, you may recall that a variable is a named pointer <strong>to</strong> a location in memory where data is<br />

s<strong>to</strong>red. In other words, variables allow programs <strong>to</strong> keep track of information over a period of time. An<br />

array is exactly the same, only instead of pointing <strong>to</strong> one singular piece of information, an array points <strong>to</strong><br />

multiple pieces. See Figure 9.1 .<br />

Variable<br />

fi g. 9.1<br />

7<br />

Array<br />

4 8 15 16 23 42<br />

You can think of an array as a list of variables. A list, it should be noted, is useful for two important<br />

reasons. Number one, the list keeps track of the elements in the list themselves. Number two, the list<br />

keeps track of the order of those elements (which element is the fi rst in the list, the second, the third,<br />

etc.). Th is is a crucial point since in many programs, the order of information is just as important as the<br />

information itself.<br />

In an array, each element of the list has a unique index, an integer value that designates its position in the<br />

list (element #1, element #2, etc.). In all cases, the name of the array refers <strong>to</strong> the list as a whole, while<br />

each element is accessed via its position.<br />

Notice how in Figure 9.2 , the indices range from 0 <strong>to</strong> 9. Th e array has a <strong>to</strong>tal of 10 elements, but the fi rst<br />

element number is 0 and the last element is 9. We might be tempted <strong>to</strong> s<strong>to</strong>mp our feet and complain:<br />

“ Hey, why aren’t the elements numbered from 1 <strong>to</strong> 10? Wouldn’t that be easier? ”<br />

Array index values<br />

0<br />

fi g. 9.2<br />

1 2 3 4 5 6 7 8 9<br />

While at fi rst, it might intuitively seem like we should start counting at one (and some programming<br />

languages do), we start at zero because technically the fi rst element of the array is located at the start of<br />

the array, a distance of zero from the beginning. Numbering the elements starting at 0 also makes many<br />

array operations (the process of executing a line of code for every element of the list) a great deal more<br />

convenient. As we continue through several examples, you will begin <strong>to</strong> believe in the power of counting<br />

from zero.

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

Saved successfully!

Ooh no, something went wrong!