Module 6: Arrays
Structured Data
An array is a data structure that holds multiple items of data under a single identifier (name). In ERL, we use 0-based indexing.
One-Dimensional (1D) Arrays
To declare an array, use the array keyword followed by the name and its length in square brackets.
array scores[5]
scores[0] = 85
scores[1] = 92
print(scores[1]) // Outputs 92
Exercise: Create an Array
Declare an array called colors of size 3. Set the first element to "Red", the second to "Green", and the third to "Blue". Print the middle element.
ex1.erl
Looping through Arrays
To access every item in an array (called traversial), a FOR loop is perfect. Since ERL arrays are 0-indexed, a size 5 array has indices 0 to 4.
array names[3]
names[0] = "Alice"
names[1] = "Bob"
names[2] = "Charlie"
for i = 0 to 2
print(names[i])
next i
Exercise: Sum of Scores
Below is an array of 4 scores. Write a FOR loop that iterates through the array, adds them all together into a `total` variable, and then prints the total at the end.
ex2.erl