Expressions with Arrays
Expressions allow you to read values from the elements of an array. To get an elements value you must supply the name of the array, and the index of the element you want to read.
Reading Elements - Why, When, and How
In most ways, accessing an array element is the same as accessing a variable. The main difference, in terms of what you can do, is that you now have the index of the element you want to read as an expression. This is huge! Think about it. You can now have other code that works out which element to access. This is what makes arrays awesome!
Let’s think about life before arrays. Say I want to read in three integer values. I can do it like this:
Each variable has a unique name, so we have lots of duplicate the code. With arrays, we can now change this up. To start with, we could code this with hard coded values. In this case we still have duplicate code, but you should be able to see that arrays are much like a number of variables used to store the same thing.
Where it becomes cool, is where we realise that the value for the index can be calculated! It can be any expression we want at all! As a first step, we could remove the hard coded indexes.
Now the code is screaming out to you to remove the repetition. We are performing exactly the same steps over and over here.
We can make this neater using for loops, but I hope you can see the potential here.
How do we now change this from working with 3 values to work with 50, 100, 1000, 10000 values? Easy! You just change the NUM_VALUES
constant. That is all.
Think about it. You now have the tools to work with large numbers of values, and it doesn’t take you much more to code this than it takes to code the actions for one value. You just add a loop, and the computer does all the hard work repeating those steps over and over for all the values you give it.