23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

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.

an array a are numbered 0, 1,2, <strong>and</strong> so on. We illustrate an array of high scores for a<br />

video game <strong>in</strong> Figure 1.6.<br />

Figure 1.6: An illustration of an array of ten (<strong>in</strong>t) high<br />

scores for a video game.<br />

Such an organization is quite useful, for it allows us to do some <strong>in</strong>terest<strong>in</strong>g<br />

computations. For example, the follow<strong>in</strong>g method adds up all the numbers <strong>in</strong> an array<br />

of <strong>in</strong>tegers:<br />

/** Adds all the numbers <strong>in</strong> an <strong>in</strong>teger array. */<br />

public static <strong>in</strong>t sum(<strong>in</strong>t[] a) {<br />

<strong>in</strong>t total = 0;<br />

for (<strong>in</strong>t i=0; i < a.length; i==) // note the use of the length<br />

variable<br />

total += a[i];<br />

return total;<br />

}<br />

This example takes advantage of a nice feature of <strong>Java</strong>, which allows us to f<strong>in</strong>d the<br />

number of cells an array stores, that is, its length. In <strong>Java</strong>, an array a is a special k<strong>in</strong>d<br />

of object <strong>and</strong> the length of a is stored <strong>in</strong> an <strong>in</strong>stance variable, length. That is, we<br />

never need to guess the length of an array <strong>in</strong> <strong>Java</strong>, the length of an array can be<br />

accessed as follows:<br />

array_name.length<br />

where array_name is the name of the array. Thus, the cells of an array a are<br />

numbered 0, 1,2, <strong>and</strong> so on, up to a.length − 1.<br />

Array Elements <strong>and</strong> Capacities<br />

Each object stored <strong>in</strong> an array is called an element of that array. Element number 0<br />

is a[0], element number 1 is a[1], element number 2 is a[2], <strong>and</strong> so on. S<strong>in</strong>ce the<br />

length of an array determ<strong>in</strong>es the maximum number of th<strong>in</strong>gs that can be stored <strong>in</strong><br />

60

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

Saved successfully!

Ooh no, something went wrong!