Lesson 15: Arrays in Action

Homework: Using an array allow a user to enter 5 numbers, then using a loop find the total and average of the numbers and output them.

Before I want to talk about arrays, I want to first talk a bit more about variables. One of the things that we’ve all wanted a user to be able to do at some point is: “Enter x variables, enter y number to stop” and then you do something with them. And the way to do this was probably with some crazy structure of a while loop, multiple ifs, tons of variables, tons of tests to make sure that stuff was used / input correctly. Arrays are the start of a solution to the issue. Arrays are a container that allow us to hold “like-type” variables (all the same type). So for instance, an array of ints can only hold ints. If we try to put in a double, it will actually work (in some IDE, others will trigger an error), but it will trim everything after your decimal place. With any of the types we’ve used thus far, we can make an array. This includes string, but that’s a little bit special since each individual string is a little bit like an array itself.

Declaring an Array
In C++ there are a few different ways to declare an array, in this lesson we looked at 2 of them. Size-known and initialized arrays. A size-known array is one where we use either a plain number (int) or a const int that is declared at compile-time to make the size of the array known. It bears mentioning that the following is INVALID

We have to be very careful that we adhere to using arrays in a way that doesn’t confuse this. There are ways to create array-like structures of unknown size that we’ll get into later, but these are not as simple or straight forward.

Some good examples of array declaration are:

What is an Array
All this talk of how to set them up, and how to make them, and so little talk of what they do. As I said earlier, an array is a sort of storage container that holds like type variables. But rather than just saying that, let me show you a case of when an array might be good (remember this example for later, we’ll touch it again in classes).

The smarter way to do this (until we get to objects) is to use arrays to contain the similar data. The above example become very complex if we ever need to edit item numbers, change prices for a sale, or output them in some way that makes sense. A better example looks like this:

Off-By-One error
The off by 1 error is going to be your all-time worst enemy. These are common with loops and have been discussed there, but they are equally common for arrays. Arrays are 0-indexed. Meaning the FIRST location in an array is array[0] rather than array[1] like a lot of people seem to try. This is going to be the primary error you run into and it will present as an Array Bounds Error (or something along those lines)

Lesson 14: Introduction to Arrays
Lesson 16: Case Study- Calculator with Switch statement