Intro to Arrays

An array is a special variable, which can hold more than one value at a time. An array allows us to store a group of items of the same data type together in memory - making it easier to process a large number of items. Because variables hold only one value, they can be cumbersome in programs that process lists of data. Processing a large number of items in an array is usually easier than processing a large number of items stored in separate variables. For example, suppose we needed to store the names of 50 employees. Declaring and inputting 50 names in to 50 different variables would be quite a chore!

Arrays are specifically designed to store and process lists of data. Just like a variable, an array is a named storage location in memory. But, an array can hold a group of values. All the values in an array must be of the same data type. We can have an array of Integers, an array of Reals, and an array of Strings, but we can not store a mixture of data types in an array.

To declare an array named units that can hold 10 Integer values, we use the following code.

Declare Integer units[10]

It looks identical to a regular Integer variable declaration except for the number inside the brackets. The number in brackets is called a size declarator and it specifies the number of values the array can hold. An array size declarator must be a nonnegative integer. We can declare an array named salesAmounts that can hold 7 Real numbers with the following code.

Declare Real salesAmounts[7]

To declare an array named names that can hold 50 String values, we can use the following.

Declare String names[50]

Most programming languages do not allow us to change the size of an array while the program is running. If we need to change the size, we have to edit the array's size declarator in the source code and recompile. To make array sizes easier to maintain, many programmers use named constants as array size declarators. For example,

Constant Integer SIZE = 10
Declare Integer units[SIZE]

We often find ourselves having to refer to an array's size, so using a named constant is convenient as we have that value readily available for our algorithms. Also, if we ever have to change an array's size, we can simply change the value of the named constant.