teach-ict.com logo

THE education site for computer science and ICT

3. One dimensional arrays

An alternative to storing all data as separate variables is to use an array.

The array is given a single name and is associated with each of the entries in it. For example:

                 football_team  ("John Smith", "Harry Potter", "Jimmy Carr", ... )

Football_team is an example of a one-dimensional array. In this case it is the names of a football squad. It will have 11 items in it.

Now let us think about storing a collection of 5 numbers. This is written in pseudocode:

                MyArray  (3,56,21,5,7)

Each item has an index (position in the array). The first item (or element) is at position zero. Arrays usually begin with position zero, not one.

 

An array is a collection of related data. Each piece of data within the array is an element. The position of each element within the array is pointed to be its index. Arrays usually begin at index 0, not index 1.

In order to access an element of an array, you use its index

Like this

                MyArray  (3,56,21,5,7)
                OUTPUT MyArray[1]

This will print out '56' because that is the element at index 1.

 

Updating an array

You can also change the value of an element by using its index, like this

                   MyArray  (3,56,21,5,7)
                   MyNumber  11
                   MyArray[4]  MyNumber

This will replace whatever was in position 4 in the MyArray array with "11". So we are replacing the number 7 with the number 11

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: What is a one dimensional array