Mwnci Arrays

What is an Array

An array is a collection of items stored at contiguous memory locations. Or in simpler terms it’s a variable that can hold more than one value.

If you have a list of items, say Doctor Who enemies, storing them in an array would be like this:

Enemies = ["Dalek", "Sontaran", "Cyberman"]

An array can hold many values under a single name, and you can access the values by referring to an index number.

Accessing an Array

Get the value of the first array item:

X = Enemies[0]

"Dalek"

Modify the first array item:

Enemies = set(Enemies, 0, "Silurian")

this can also be done using the following method:

Enemies = Enemies.set(0, "Silurian")

The Length of an Array

The length of an array (the number of elements) is found by using theĀ len() builtin function.

X = len(Enemies)

4

The length of an array is always one more than the highest array index.

Looping through the Array

The foreach loop can be used to loop through all the elements of an array

Print each item in the Enemies array:

foreach x in Enemies {
    println(x)
}

Silurian
Sontaran
Cyberman

Adding Array Elements

You can use the push() builtin command to add an element to an array.

Enemies=push(Enemies, "Macra")
or
Enemies=Enemies.push("Macra")

["Silurian", "Sontaran", "Cyberman", "Macra"]

Removing Array Elements

You can use the delete() builtin command to remove an element from an array.

Enemies=delete(Enemies, 1)
or
Enemies=Enemies.delete(1)

["Silurian", "Cyberman", "Macra"]

Adding Array Elements

You can use the push() builtin command to add an element to an array.

Enemies=push(Enemies, "Macra")
or
Enemies=Enemies.push("Macra")

["Silurian", "Sontaran", "Cyberman", "Macra"]

Replacing Array Elements

You can use the set() builtin command to alter an element in an array.

Enemies=set(Enemies, 1, "Weeping Angel")
or
Enemies=Enemies.set(1, "Weeping Angel")

["Silurian", "Weeping Angel", "Macra"]