Array
An array is a special kind of variable, one that stores multiple values instead of a single value. The values within an array, called elements, all have the same type.
Arrays - Why, When, and How
Arrays are another tool that will greatly help you build bigger and more interesting programs. Once you get your head around how they work, you will be able to easily add arrays to your programs to make it easy to add lists of values wherever you need them. You can add arrays to fields of a struct, so you can have multiple values within that entity in your code. You can use arrays of structs to have lists of your entities. They can be local variables and passed as parameters. Anywhere you had data before, you can now start to use arrays.
You need to pair arrays with a loop to repeat actions you want performed to each element of the array. You can then have any number of elements in the array, and a simple loop repeats your instructions for all elements. It is a really simple and effective way to start to grow out what you can do.
One challenge we currently have is that our arrays will have a fixed size. We can work around this by having a maximum number of values that we want to allow within the array, and then have a variable to track the current number of elements that we increase and decrease as we add or remove elements.
Arrays in Memory
Arrays store multiple values, with an index that provides access to the individual elements within the array. Conceptually this can be viewed as a variable that contains multiple slots (the elements) into which the values are stored.
Many languages have 0 as the index of the first element. This reflects how the values are actually stored in memory. Figure x.y shows how an array (named arr
in this Figure) is stored in memory. The array is a contiguous area in memory, with the elements next to each other. You can think of the array as starting at the first element, so you need to skip 0 elements to access the first element. The second element is accessed by skipping 1 element, so it has index 1. The third element is accessed by skipping 2 elements, so it has the index 2, etc.
The size of each of the elements of the array can then be used to quickly locate it, given its index. If you have an array of integer
values, then these are each 32 bits (4 bytes), so the element at index 3 is 3 × 32𝑏𝑖𝑡𝑠 (96 bits) past the start of the array.
The great thing is that you do not need to think about these details, but knowing this should help you remember that the first element of an array is at index 0.
Example
We can use arrays to further adjust some of the programs we have been working with so far. We can extend the Fly Catch game, so that the game has a number of flies. In the change calculator we can put our different coins into an array, further simplifying the process of calculating change. In each case, the array lets us easily store a number of values in a single variable.