This lesson introduces arrays as a means of storing lists of information within a program. The class begins by highlighting the difficulties that arise when trying to store lists of information in a variable. Students will then watch a short video introducing arrays and a subset of the operations that can be performed with them. They will work in the online or offline IDE for the remainder of the class as they practice using arrays in their programs. At the conclusion of the sequence, students build a simple app which can be used to store and cycle through a list of their favorite things. In the next lesson, they will continue working with a version of this app that can display and cycle through images, not just text strings.
Students will be able to:
Some sort of list data structure is a component of almost all programming languages. A list allows large amounts of information to be easily referenced and passed around a program, and the use of a numeric index allows individual items in a list to be accessed. Historically a list would have literally been a single contiguous chunk of memory and the index or address was used to know how far into that chunk a relevant piece of information was stored. In many modern languages, however, it is more likely that the items in an array are stored at many locations on your computer's hard drive, and the index is only useful to help the programmer identify different components. In this way, a Quorum Programming Language's array is actually another example of abstraction. We know that it is holding a list of related information, but we don't need to think about the actual implementation details.
Today we're going to start examining how we can use lists in programs, but before we dive into that, let's think about why we would want to in the first place. What are the benefits of creating lists? Why is it helpful to keep information in lists?
There are a lot of benefits to keeping lists of information in real life. Since we use programming to solve a lot of similar problems, we would like to keep lists of information in our programs, too. Right now, the only way we know how to store information in our programs is with a variable, but each variable can only store a single piece of information. Today we'll be learning about a new programming construct that will allow us to hold as many pieces of information as we want within a single list.
The following video explains several properties of lists that will be explored in this lesson's programming exercises.
This lesson's programming exercises are designed to introduce students to Arrays. The first exercise introduces how indexing works with Arrays. Next, students use an Array to perform arithmetic between values at different indexes. The subsequent exercise teaches students how to remove a value from an index in an Array. Then students are walked through an example of code that demonstrates how to insert values into an Array at a certain index. Finally, students learn how to use the "Size" action of an Array to get the number of elements contained inside it.
After learning how to use Arrays, students conclude this activity by creating the "My Favorite Things" App, a program that uses an Array of text variables and allows user input to retrieve the data stored at a specific index, or to insert new data at an index.
Arrays have many features which make them different from variables and/or objects, but most of what you've learned about variables and/or objects also applies to arrays. For example:
Consider the following code.
use Libraries.Containers.Array Array<integer> arrayOfIntegers arrayOfIntegers:Add(100) arrayOfIntegers:Add(250) arrayOfIntegers:Add(500)
We specified this array to contain integer type values, and called it "arrayOfIntegers." We called the action "Add(integer)" to add integer values to this array. This array contains 3 values: 100, 250, 500.
In Quorum, you can get specific data stored in an Array. Let's use the array that we created in the example above. In this array, we have three index positions: 0, 1 and 2. The index position in an array always starts from "0." In this array the index "0" contains the integer 100, "1" contains 250, and "2" contains 500.
There are several actions we can use to retrieve data from an array in the Quorum Programming Language. In this section, we will learn how to retrieve a value from a specific index position.
Let's use the array we created in the code example above, and retrieve the data in position "1."
integer value = 0 value = arrayOfInteger:Get(1) output value //(Or, just simply:) output arrayOfInteger:Get(1)
When you run this code, you will get the output "250," because the index "1" contains the integer 250.
Create an array that contains the integers from 1 to 10 in the first ten index positions (0 - 9). Retrieve the data from a specific index to check that your array is working. Run the code several times while changing the index position.
We can use any expression that evaluates to a number as an index in an array. Here are some examples:
ArrayOfIntegers:Get(2 + 3) ArrayOfIntegers:Get(X + 4) ArrayOfIntegers:Get(random:RandomIntegerBetween(0, 9))
You can reference locations in arrays within arithmetic expressions, just like you might with a variable.
You will be modifying the code in your program (from the previous exercise) that calculates the sum of the values in the array. Let's say you would like your program to add the data at index "0" and index "9." There are several ways to do this, but one example is:
value = arrayOfIntegers:Get(0) + arrayOfIntegers:Get(9) output value
Try creating other types of Arithmetic calculation using arrays.
You can also remove an existing value from a specific index position. When you do this, however, remember that the value inside the same index position is replaced by the value that previously followed it. This means that you are shortening the length of array by one when you remove one value. For example, when we have the following code segment:
integer value = 0 value = arrayOfIntegers:RemoveAt(4) output value output arrayOfIntegers:Get(9)
This code will give you an error saying something like "There is no such index position in your array." You need to change the "Get(9)" action call to "Get(8)," to retrieve the expected value of 10. This is because, after the "RemoveAt(4)" action call, the resulting array contains the list of (1, 2, 3, 4, 6, 7, 8, 9, 10)
Go ahead and try removing a value in a index, then retrieve a value in newly refreshed index position.
Now, assuming you have tried the previous exercises, we will now learn how to place a new value in any index position, thus extending the length of index by one. We start the process with observing the following code:
use Libraries.Containers.Array Array<integer> arrayOfIntegers arrayOfIntegers:Add(1) arrayOfIntegers:Add(2) //(Keep adding the consecutive number up to 10) integer value = 0 value = arrayOfIntegers:RemoveAt(4) output value output arrayOfIntegers:Get(8) arrayOfIntegers:Add(4, 20) output arrayOfIntegers:Get(9) output arrayOfIntegers:Get(4)
When you run this code, you should get the output:
5 10 10 20
This means that you array now have the list of (1, 2, 3, 4, 20, 6, 7, 8, 9, 10).
Quorum Programming Language has a special function that allows a programmer to write a simple code without establishing formal code structure in the code. Up to this point in this lesson, we have been taking advantage of this function of the language to make our learning easier for the topic of arrays. When we start creating actions, however, the Quorum language will require us to establish a structure in the code. The following code example shows how to structure our code, as well as how we can create an action for replacing the value at specific index position in an array.
use Libraries.Containers.Array class Main Array<integer> arrayOfIntegers action Main arrayOfIntegers:Add(1) arrayOfIntegers:Add(2) // (Keep adding the number up to 10) ReplacingValueAt(4, 20) output arrayOfIntegers:Get(4) end action ReplacingValueAt(integer index, integer value) arrayOfIntegers:RemoveAt(index) arrayOfIntegers:Add(index, value) end end
We have encountered this kind of structure so many times already in the previous lessons, even back to Unit 3. The first and most important idea of formal structuring is "A program needs to have a class 'Main' that has an action 'Main' inside of it."
When we have this base structure to start with, then we can write another action outside of the action "Main," and call the action in the action "Main." The computer only executes whatever appears in the action "Main."
The rest of this code should be relatively self explanatory. We just created the action "ReplacingValueAt(integer index, integer value)" that calls a couple of actions (we have learned previously) inside. Then we called this action in the action "Main" so that the computer will execute the action with the specified parameters.
So far we have been using arrays to hold integers, but each location in an array could hold other type of values instead. The following are examples:
use Libraries.Containers.Array Array<number> arrayOfNumbers arrayOfNumbers:Add(2.04) arrayOfNumbers:Add(3.45) arrayOfNumbers:Add(12.67)
Array<text> arrayOfTexts arrayOfTexts:Add("John") arrayOfTexts:Add("Alexis") arrayOfTexts:Add("Michael")
As we saw in the previous exercise, there are many strange behaviors that can result from referencing array indexes that are less than 0 or greater than the highest index in your array. To help avoid these kinds of errors, it is useful to know how long your array is, especially since we know that arrays can grow and shrink during the course of our program.
You can always check the current length of your array by calling the action "GetSize" on an array object. It evaluates to a number indicating how many items are in your array.
Remember: this is NOT THE INDEX NUMBER. This is the size. If the size is (10), your array has indexes from 0 to 9.
Copy your code from the previous exercise into the below IDE. Place the line of code above at the end of action "Main" in your ongoing code to check the size of your array.
We have been accessing information in an array by using numbers, but we can actually use any expression that evaluates to a number as an index in our array. The first example of this we will explore is accessing the last item in our array.
Arrays are zero-indexed, which means that the first index is 0. Therefore an array with a length of 3 will have indexes 0, 1, and 2. Notice that the last index is 1 less than the length. This will always be the case, and so we can use this expression to access the last element in any array:
arrayOfIntegers:Get(arrayOfInteger:GetSize() - 1)
Check out this simple app for creating a collection of your favorite things. We're going to be working towards building this app over the next several exercises. As you might expect, this application uses an array to store and organize information.
Use the "My Favorite Things" app and try to predict how arrays are used to create the functionality you observe. Some features to notice are:
Let's create an Array of text variables, and then add five text values in it. Your code should be similar to this:
use Libraries.Containers.Array Array<text> myFavorite myFavorite:Add("Succor") myFavorite:Add("Video Game") myFavorite:Add("Eating Out") myFavorite:Add("Drawing") myFavorite:Add("Jogging")
You have learned all the coding syntax required to create this mechanism. This part of the code should be something like this:
text userInput = input("Enter the index number to retrieve the information. The current highest index number is " + (myFavorite:GetSize() - 1) + ". If you would like to add new information in the current index position, type in '-1'.") integer userChoice = cast(integer, userInput)
We need to use some new sytax for this part. You need to call an action from the Array class on your array object. The action is "Add(index, value)." That part of the code should be something like this:
integer currentIndex = 0 //This variable needs to be declared before any structure. text newInput = input("Add a new value at the current index") myFavorite:Add(currentIndex, newInput)
This is a tricky one, but we will use the if-elseif-else statement structure to create this mechanism. For the purpose of this code, we will have the user input any negative number to give them a chance to input new information. So, the "if" part would be:
if userChoice < 0
Now, for the "elseif," we will use the (Size - 1) expression so that the user input does not go beyond the size of the array. So, the code would be:
elseif userChoice <= (myFavorite:GetSize() - 1)
For the "else," we will output a warning to the user that the number is exceeded the boundary of the array. The code should be something like:
else output "The index number does not exist at this point." end
Finally, if you just use this if-elseif-else statement, you need to re-run the program each time you want to determine how it works. So, for the purpose of your observation, let's enclose this if-statement inside of a "repeat 5 times" loop. Thus, the empty structure of this code should be something like:
// (use statement) // (Instantiating an array object) // (Adding Initial data in the array) integer currentIndex = 0 repeat 5 times //(Getting the user input and casting goes in here) if userChoice < 0 //(Getting new information from the user goes in here.) elseif userChoice <= (myFavorite:GetSize() - 1) //(outputting current array size, current index, and the information at the index goes in here) currentIndex = userChoice else output "The index number does not exist at this point" end end
Using the template above as a guideline, put the previous code blocks (after the heading "My Favorite Things" App) together to complete the app. Test the app several times to observe and learn how the array works in the active program. If you are using the online IDE below, note that you will be prompted all five inputs before the output is reflected on the screen.
Your app should now be fully functional - nice job! There are, of course, plenty of new pieces of functionality that can be added. If you have time, feel free to make any improvements you wish. Here are some ideas:
Students now know how to store information in both variables and arrays. The following prompts should synthesize their new knowledge by trying to develop a rule for when to use a variable vs. an array.
Your app needs to store the following information. Decide whether you should use an array or a variable to store it.
In general, when do you think you should store information in an array, and when should you use a variable?
We are going to keep exploring arrays in the coming lessons. Encourage students to consider some of the distinctions we just discussed, and to keep thinking about how they might want to use arrays in applications of their own.