16 / 16

Arrays

Sometimes we need to handle many values of the same type, that are somehow related.
For example we can have:

  • an array of student grades (Array[Integer])
  • an array of temperature measurements (Array[Real])
  • array of pet names (Array[String])
  • array of switch states, on or off (Array[Boolean])

Arrays have a fixed length.
You can get array's length with the function length(array).


Array items are accessed by their index (position in the array), using brackets syntax.
The first index is 0 and the last index is length(array)-1.
For example, if we have array: Array[Integer] with values [1,2,3] then:

  • its length is 3
  • its indexes are 0, 1 and 2
  • its items are array[0], array[1] and array[2]

The For loop is ideal for iterating through the whole array.


Let's make a program that calculates average grade (range 0 to 100) using an array.
Steps:

  • declare grades: Array[Integer] of length 3
  • assign grades[0] = 30
  • assign grades[1] = 50
  • assign grades[2] = 100
  • add a For loop that goes from 0 to length(grades)-1
  • assign sum = sum + grades[i] in the For loop body
  • after For loop add output "Average grade is " + sum / 3.0

The program will output Average grade is 60.