Skip to main content

Chapter 3 Arrays

Chapter 2 gave you a good overview of what variables are, how to use them, and why they are important in programming. We have discussed when to use different types of variables such as Integer variables and String variables and how to assign and change their value. However, the types of variables we have talked about so far seem to only store one piece of information at a time. I hope you can see how this approach can be very tedious for storing lots of information. In this chapter, we will talk about other types of data containers and what it means to create your own data type. Lastly, we will close with some practice problems to help deepen your understanding.

So far we have seen examples like the following

Integer one Integer two Integer three

In this example, variables one, two, and three each can only hold one integer.

So in order to store three pieces of information we need to create three variables. This is very tedious to write, imagine if you need 100, 1000, or even 1,000,000 variables to hold data. Would you have to create many variables each with unique names to store the data in? The answer to that question is no. There are certain types of variables that allow you to access multiple data storage locations with the use of only one variable that only needs to be declared once.

An Array is a special kind of variable that can give you access to more than one data storage location. You can think of it as a chain of variables of the same type glued together.

Accessibility Description
Figure 3.0.1. Array
Exercises Exercises

1.

Provide examples of where you might want to use an array to collect data

In technical terms. An array is a collection of contiguous memory locations. In order to declare an array you tell the program what type it is, meaning the type of data it will be holding and how many slots of memory spaces you will need. Below is an example

Remember: not all programming languages require you to declare a variable before an assignment.
Arrows point to the different parts of the array declaration statement
Figure 3.0.2. String array[10]

You might be wondering what the square brackets are and also the number inside them. In many programming languages and in the pseudocode we will be using in this book, variable names with square brackets after them denote arrays and the number inside them is the size of the array. The number inside the square brackets must always be an integer because that denotes how many slots of space to allocate.

Examples:

(visual aid)
Figure 3.0.3. Integer array[5]
(visual aid)
Figure 3.0.4. Integer array[15]
Exercises Exercises

1. Arrays - Fill in the blanks.

The data type of the array is .The size of the array . The array name .