15.04.2018 Views

programming-for-dummies

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

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

586<br />

Data Structures<br />

Creating an array<br />

To create an array in Pascal, you must create a variable that represents an<br />

array under the Var section of a program like this:<br />

Var<br />

Arrayname : ARRAY [LOWER..UPPER] OF datatype;<br />

If you wanted to create an array to hold five strings, you could do this:<br />

Var<br />

HitList : ARRAY [1..5] OF string;<br />

If you don’t want your array elements to be numbered from 1 to 5, you could<br />

pick any range of numbers, such as<br />

Var<br />

HitList : ARRAY [25..29] OF string;<br />

Defining different lower and upper ranges <strong>for</strong> the size of your array gives you<br />

the flexibility of using meaningful array index numbers (such as employee<br />

IDs), but at the risk of making the actual size of the array harder to understand.<br />

An array bounded by 1..5 easily identifies five elements in the array,<br />

but an identical array bounded by 25..29 also identifies five elements in an<br />

array but it’s not as obvious.<br />

You can also create a dynamic array that can change in size while your program<br />

runs. To create a dynamic array, define the array without specifying its<br />

size, such as<br />

Var<br />

Arrayname : ARRAY OF datatype;<br />

Be<strong>for</strong>e you can store data in a dynamic array, define its size with the<br />

SetLength command, such as<br />

SetLength (Arrayname, Size);<br />

So if you created a HitList dynamic array, you could define its size to hold<br />

ten items by using the following:<br />

SetLength (HitList, 10);<br />

When you define the size of a dynamic array, you define only the size of the<br />

array because the first element of the array is always 0. When you want to

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

Saved successfully!

Ooh no, something went wrong!