15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

318<br />

Using an Array<br />

Some <strong>programming</strong> languages let you initialize an array without a loop.<br />

Instead, you declare an array and its initial data on the same line. This C++<br />

code declares an array that can hold five integers and stores 0 in each array<br />

element:<br />

int lotterynumbers[] = {0, 0, 0, 0, 0};<br />

Storing data<br />

To store data in an array, you need to define two items:<br />

✦ The array name<br />

✦ The array element where you want to store the data<br />

So if you wanted to store data in the first element of a zero-based array, you<br />

could do this:<br />

int myarray[5];<br />

myarray[0] = 357;<br />

If you wanted to store data in the first element of a one-based array, you<br />

could do this:<br />

Dim myarray(5) as Integer<br />

myarray(1) = 357<br />

You can store data in array elements in any order you want, such as storing<br />

the number 47 in the first array element, the number 91 in the fourth array<br />

element, and the number 6 in the second array element, such as<br />

int myarray[5];<br />

myarray[0] = 47;<br />

myarray[3] = 91;<br />

myarray[1] = 6;<br />

Retrieving data<br />

To retrieve data from an array, you need to identify<br />

✦ The array name<br />

✦ The array element number that contains the data you want to retrieve<br />

Suppose you had the following BASIC code that creates an array that stores<br />

three names:

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

Saved successfully!

Ooh no, something went wrong!