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 (
Integer[]) - an array of temperature measurements (
Real[]) - array of pet names (
String[]) - array of switch states, on or off (
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,1and2 - its items are
array[0],array[1]andarray[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 length3 - assign
grades[0] = 30 - assign
grades[1] = 50 - assign
grades[2] = 100 - add a
Forloop that goes from0tolength(grades)-1 - assign
sum = sum + grades[i]in theForloop body - after
Forloop add output"Average grade is " + sum / 3.0
The program will output Average grade is 60.