Looping through Arrays

So far we have used variables that are of the four basic types: Boolean, Real, Integer or String.

We can also have an array using any of those types. This means that we have several spaces in memory that we can refer to using the same variable name.

In order to declare an array, we tick the array checkbox when declaring a variable, and enter the array size.

Declair array properties

Each location within the array is referenced by using the name of the array, followed by the numerical location. Arrays start at location 0 and continue until they hit the end of the array which is the size. An array of size 3 will then have locations: myCars[0], myCars[1] and myCars[2]

We can assign values into the array locations by saying:

myCars[0] = 2000

myCars[1] = 3550

myCars[2] = 1400

An easier way to do this is to loop through the array, using a variable whose value is the same as the array location.

Such as a variable index = 0, then we can say myCars[index] = 500. See the following examples for how to do this with either a while loop or a for loop.

Looping through an array with a while loop

Looping throug with while loop

Looping through an array with a For loop

looping with for loop

results matching ""

    No results matching ""