Arrays are one of the most valuable tools we have as programmers, and it's nearly impossible to make a large and complex program without them. However, they can be daunting for newcomers. I've tried to make this lesson approachable and easy to understand, so you can be programming with arrays in no time
This two-part lesson covers arrays, which are used to store collections of information in list or table format. If you need to store many values and giving each one its own variable name is unmanageable, arrays are the answer. We will go over some basic definitions, the structure of arrays, and then how to use them.
General concept and definitionsEdit
In general terms, an array is a collection of variables that are referred to by a number instead of a name. Arrays are more or less identical in concept to mathematical matrices. If you need to store a large amount of information in a list or a table, arrays are the tool you use. Arrays have a property called dimension that is analagous to dimensions in a mathematical space or graphics. In Petit Computer, arrays can be one-dimensional (1D) or two-dimensional (2D). We'll go over this soon.
Again, an array is a collection of unnamed variables. Each variable in an array is called an element, and you access an element by its index, which is a number denoting its position in the array. Elements in an array must usually be of the same type. In Petit, you can make arrays of numbers and arrays of strings, but not an array that contains both numbers and strings.
Don't worry if this all sounds confusing, it's actually fairly simple.
Think of a 1D array as a list. You use a 1D array just like a list, to store a collection of separate but related values. For example, you might want to store names for five different characters: "Luke", "Han", "Leia", "Chewie", "Lando". That's a list, so you can store it in a 1D array.
You declare a 1D array like this:
The DIM command creates an array with the name you provide, in this case NAMES$ (as with variables, a $ at the end of the name indicates the array contains strings). The number in parentheses is the size of the array. We just created an array of strings with space for 5 elements.
You store or load a value from an array like this:
NAMES$ = "Luke"
NAMES$ = "Han"
NAMES$ = "Leia"
NAMES$ = "Chewie"
NAMES$ = "Lando"
PRINT NAMES$ 'prints Luke
PRINT NAMES$ 'prints Han
After we create the array, we access elements in the array by using the array name followed by the index in parentheses. In the above example, Luke is at index 0 and Han is at index 1, etc. Again, the index refers to the position of a value in the array, and the first index is always 0. In this example, the array has a size of 5 with indexes 0 - 4. This is called 0-based indexing. It is very important to remember the first index is always 0 and the last index is 1 less than the length.
You can (and often should) access an index with a variable:
NAMES$[X] See "Forget your indexes!" for more about this.
If you find the  brackets to be inconvenient (as they require the shift key to be tapped, or the L or R shoulder buttons to be held), you can use parentheses instead; just be careful not to confuse arrays and functions.
Think of a 2D array as a spreadsheet with rows and columns. You should use them when you have several objects with the same properties; for example, if you had several weapons that had a damage, rate of fire, and range.
You declare and use a 2D array like this:
GUNS[0,0] = 5 'damage
GUNS[0,1] = 2 'rof
GUNS[0,2] = 25 'range
GUNS[1,0] = 8 'damage
GUNS[1,1] = 4 'rof
GUNS[1,2] = 10 'range
This creates an array with 2 rows and 3 columns. Notice a 2D array has 2 indexes. The first index in a 2D array is row, and the second is column. The image to the right should help you make this connection.
That covers array syntax, next we'll go over usage.
- Tip: If you have trouble visualizing your 2D array or keeping track of the indexes, you might want to print or draw a reference table and keep it next to you when coding.
- Tip: Indicate the purpose of each column in a 2D array with a comment immediately above the DIM line
Now that we know the basics of arrays and have some idea how to use them, we can look more into when and how to best use arrays.
As a general note, every element in a new number array starts with a value of 0, and every element in a new string array starts with a value of "" (an empty string)
Arrays cannot change in size after they are created; if you aren't sure how many values will end up going into an array when the programming is running, you'll have to guess an appropriate size and then check at runtime to make sure you don't exceed the size of the array. To make this easier, you should usually create a variable just for the size of the array:
MAXFRIENDS = 5
'last valid index is MAXFRIENDS - 1
IF (INDEX >= MAXFRIENDS) THEN PRINT "ERROR: Array is full":END
FRIENDS$[INDEX] = NEWFRIEND$
- Tip: Use a separate variable like NUMFRIENDS to track how many indexes are currently full
- Tip: If you often find your array is running out of space, you might want to make it bigger
Using arrays with loopsEdit
Since indexes are accessed by number, arrays go hand-in-hand with loops.
'Print the whole array
FOR X = 0 TO MAXFRIENDS - 1
'Only print indexes that are in use
FOR X = 0 TO NUMFRIENDS - 1
We can use nested loops to move through all of a 2D array.
FOR Y = 0 TO MAPROWS - 1
FOR X = 0 TO MAPCOLS - 1
Often you will find that you need to associate both strings and numbers with an object. What if you want three characters to each have a name, a height, and a weight? In this case, you want to use parallel arrays - arrays that are the same length and related by index
MAXFRIENDS = 3
DIM FRIENDVALS[MAXFRIENDS, 2]
FRIENDS$ = "Todd"
FRIENDVALS[0, 0] = 72 'height, inches
FRIENDVALS[0, 1] = 200 'weight, pounds
PRINT FRIENDS$ " is " FRIENDVALS[0, 0] " inches tall "
PRINT "and weighs " FRIENDVALS[0,1] " pounds!"
Here, we use the index 0 to refer to the same person in both arrays; in the spreadsheet analogy, we can think of FRIENDS$ as an extra column alongside FRIENDVALS.
Using DATA and READ to populate arraysEdit
This section is a work-in-progress
If you have an array with 50 elements it can get tedious to type in
- ARR = 2
- ARR = 3
- ARR = 5
- ARR = 7
- ARR = 11
Luckily, the DATA and READ commands are available to simplify the process of loading default values into an array. We use DATA to declare a set of values and then READ to 'read' them into the array. Let's use the 5 values from the previous example to demonstrate:
- DIM ARR
- FOR X = 0 TO 4
- READ ARR[X]
- NEXT X
- DATA 2, 3, 5, 7, 11
We use the DATA command to declare the values that will go into the array; each value is separated by a comma. The READ command then feeds these values into ARR, one at a time. READ ARR[X] basically says "take the next value from the DATA and put it into ARR at index X". Notice that we list the DATA after the READ command; this is somewhat counter-intuitive, but it is common to put all of your DATA at the very end of the program and read it elsewhere. There's a lot more to DATA and READ but I'll try to stick to the basics here.
You can use DATA with 2D arrays:
- DIM ARR[3,4]
- FOR X = 0 TO 2
- FOR Y = 0 TO 3
- READ ARR[X, Y]
- NEXT Y
- NEXT X
- DATA 10, 5, 8, 2
- DATA 10, 6, 8, 4
- DATA 16, 8, 4, 4
Notice we can declare our DATA on multiple lines. READ doesn't care how our data is separated into lines, although you should always format data for 2D arrays in the same way it will be stored in the array (one row per line).
Forget the indexes!Edit
As you've seen with FOR loops, we can access array elements using a variable for the index. This gives us the power to "name" our indexes and make our code much more readable!
DAMAGE = 0
ROF = 1
RANGE = 2
UZI = 0
GUNS[UZI, DAMAGE] = 5
GUNS[UZI, ROF] = 2
GUNS[UZI, RANGE] = 25
However, you must be extremely careful not to change the values stored in the variables that represent the indexes. If you forgot DAMAGE referred to an index and later wrote DAMAGE = 10, the next time you called GUNS[UZI, DAMAGE] you'd get an error!
That wraps up our array basics. If you are feeling very comfortable with arrays, you can check out advanced array topics.
- List taker - ask the user how many values they will enter, have them enter the values one at a time, then print the values back to them
- Memory - a memory game where the player must remember and repeat a sequence, with one more step added each time
- Tic-Tac-Toe - using a 2D array to store the board
- A 2D array is sometimes referred to as an "array-of-arrays" because it's basically an array of 1D arrays, but it's much easier to think of it as a table/spreadsheet