Arrays

An array is a way of grouping and storing data values that are all related and all of the same data type.

When we normally declare a variable we are creating a space in the computer’s memory to store one item of data. If we used this method to store a class set of names, we would need to create a variable for each student which would be time consuming.

The array allows us to create a group of variables of a fixed size to store our data. Each data item is stored in a separate element inside the array.

The elements in the array are numbered, this number is called the index.

Example

Pseudocode

Declaring an array

We have to declare an array in a similar way to declaring a variable.

Arrays have a fixed size which must be specified.

If we had a class of 20 students we could declare 20 variables of type string to store their names, or we could create a string array with 20 elements….

Assigning Values

Assigning values, is then like assigning to any other variable.

We use the index to identify which element to put our value into.

However…

...be careful not to try and access an array element that does not exist, this is known as an out of range error.

Assigning Multiple Values

It is possible to assign a SET of values to an array.

Reading from an array

To get your data out of the array is simple, again this works in the exact same way as variables but you use the index.

01 DECLARE exampleArray : ARRAY[1:3] OF INTEGER

02

03 exampleArray[1] ← 1;

04 exampleArray[2] ← -3;

05 exampleArray[3] ← 7;

06

07 OUTPUT("The value in the array index 1 is: ", exampleArray[1])

08

09 //we could also use a variable for this

10

11 int currentIndex = 2;

12

13 OUTPUT("The value in the array index " , currentIndex , " is...")

13 OUTPUT(exampleArray[currentIndex])

Key Words

Array

A data structure that groups together a group of variables (or elements) of the same data type that makes them accessible using a single identifier and an index number.

Index

A number that is used to identify an individual element in an array.

Out of Range Error

An error that is received when your code tries to access an element that does not exist. For example trying to access element 100 of an array that only has 10 elements.