Arrays

An array is one method of storing data in an organised structure.

Imagine you were making a game and you wanted to store player names and their scores. You would need to write some code to tell the program to store this information.

When arrays are created, the program needs to know their size. It needs to know how many player names and scores you want to collect. When an array or any variable is created in a program this is called declaring. For example, if you created two arrays which could store five pieces of data each for player scores and player names, they would be declared with the following:

  • gameScores[5]
  • playerNames[5]

An array stores a set of data elements in a certain order. A data element is any single unit of data within a program. You can tell the program exactly what the names and scores are by writing the following:

  • gameScores = (124, 99, 121, 105, 132)
  • playerName = ("Katie","Patrick","Tom","Rosie","Michael")

Arrays do not store mixed data types. The first array is a collection of numbers showing the five scores. Each data element is an integer. The second array is a collection of names. Each element is a character string.

Each element in an array relates to a specific place in memory. You could imagine this to be like shelves in a cupboard. The array is the cupboard with shelves inside it, and each shelf is numbered and used to hold a specific item.

Graphic depicting supermarket shelves and the method used to classify items by type

Did you know?

Arrays use brackets at each end with commas used as separators between the data elements. But the type of brackets varies across languages. For example, the gameScores array would be different in PHP and Visual Basic:

  • In PHP: $gameScores = array(124, 99, 121, 105, 132)
  • In Visual Basic: Dim gameScores = New Integer() {124, 99, 121, 105, 132}

These are both one-dimensional arrays - they can be seen as numbers organised in a row.