Arrays

By now you should be comfortably familiar with the basic data types in Yas: numbers, strings, booleans and null. However, each value and variable we've encountered has been a scalar value, meaning it referred to exactly one datum (singular), or piece of information. We will now begin to consider structured data, i.e. entities and objects that encapsulate multiple data (plural), or pieces of information, under a common variable name. The first data structure we will encounter is an array.

Defining and Using Arrays

Suppose we wanted to calculate the grade average for a semester's worth of classes for a student. We could save each grade in a variable, like so:

let grade1 = 90
let grade2 = 88
let grade3 = 95
let grade4 = 93
let grade5 = 99

let average = (grade1 + grade2 + grade3 + grade4 + grade5) / 5
print average

This program is not ideal: What if the student had a different number of courses in a certain semester? To add another grade, we would have to modify almost the entire program, and that seems like a chore. We can make it easier on ourselves to support any number of grades using an array instead.

An array can be thought of a numbered list of variables. To construct an array, use the [] characters around a comma-separated list of values:

let grades = [90, 88, 95, 93, 99];

We have defined the grades grades variable and assigned an array of numbers to it. The number of elements in the array is the length of the array. To find the length of an array, use the built-in function len():

console

We refer to each value stored in the array as an element of this array. Each element in the array has a unique numeric index. We can refer to each individual element of the array by appending its index, wrapped in square brackets []:

print grades[0]      # first element has 0 index
print grades[1]
print grades[2]
print grades[3]
print grades[4]      # last element has index len() - 1

We can also change the data in the array by assigning to the array element:

grades[0] = 98     # student has improved the grade, we can change it.

Zero-based Array Indexing

The array indices are zero-based: The very first element of the array has index 0 (zero), which makes the very last element of the array have index len(array) - 1.

This is an important point that you should always keep in mind: the index of an array item is always one less than the actual position of an item in an array as we say it in English: first is 0, second is 1, third is 2, etc. Programmers often refer to the first element as the "zeroth" element and refer to all items by their zero-based indices to avoid confusion.

This somewhat counter-intuitive practice has to do with how the arrays are actually laid out in consective cells of computer memory: the array variable is a "pointer" to the head of the array, i.e. the first element, and each element's index is simply the distance between the head and the element. For the head itself, this distance is equal to zero, therefore the head (being the very first element) has the zero index. For the second element, the distance from the head is equal to 1, etc.

Going Past the End

If you try to access an element of the array that does not exist, you will get a null value back:

print grades[99]     # null (there are only 5 grades)

You can add more elements to the end of the array by simply assigning them to the indices you want, as long as it's an integer:

console

Note that you're not limited to appending to the end of the array. You can assign to any index you want. Suppose we did this:

grades[9] = 96

This will makes the length of the grades array to be equal to 10 (since the largest index is now 9), but all the elements in the middle that we have not assigned will continue to have a value of null:

console

The last print command has output our (long array) as one single line of text. We can use the pretty() builtin function to make the output format a little nicer:

console

Empty Array

You can define an empty array:

let A = []
print len(A)

The length of an empty array is zero.

Arrays and Loops

Now that we have arrays as numbered lists of values, it is easy to loop over the elements of an array and make calculations. Turns out that this is a very powerful construct that allows us to handle large amounts of data while not writing a lot of code.

Greeting All Users

Let's greet some users!

console

Note the use of the _ magic variable inside the times loop as the index into the array of values. It is not exactly a coincidence that both the magic variable and the array indices start at 0. This allows us to easily iterate through the array data without "off-by-one" errors or using additional variables.

Search For an Element

Suppose we wanted to check if a particular name was in our list of students. Let's write a function that searches the array until it either reaches the end or finds an element whose value is the name we're looking for. If it finds the name, it will return its index in the array. If it reaches the end without finding our desired name, it will return -1, which will mean "not found":

console

Calculate Average

Finally, we're ready to create our grade average calculator. Let's make it a function named gradeAverage that will accept an array of numbers as its only argument and return the average of these numbers:

console

Note how the gradeAverage function is scalable: it does not matter how long the array of grades is - our function will always return the average of all the numbers. All we need to do is pass it another array with different elements.

Exercises

Name of the Month

Prompt the user for a month number (1-12) and print the English name of the month (January, February, etc.). Be sure to use an array of month names to look up the proper value. Reject and report any invalid user input as an error in the console.

console

Array Maximum and Minimum

Write a pair of functions arrayMax and arrayMin that will return the maximum and the minimum number in a given array. If the array is empty, return null from each function.

console

Back (060-functions)
Forward (080-string-operations)