17. Arrays
Arrays are used to store multiple values of the same data type in a single variable. If, for example, a program needs to store five integers, a single array can store the values rather than five separate integer variables.
Declaration
An array is itself a variable so it must be declared. The general form of an array declaration is as follows:
data-type array-name[size];
The data type indicates the kind of data to store in the array (e.g., characters). Any data type may be used. One important restriction is all values in an array must have the same data type. We cannot, for example, create an array to store a combination of floating-point and Boolean values.
An array, like any other variable, must be given a name. The name selected should follow the guidelines from the Variables section.
The brackets in a general form normally indicate an option. In this case, however, the brackets and the value within them are required. When an array is declared, a value for the size of the array must be provided so the memory allocated is large enough to store all the desired values. For example, if we declare an array to store the five integers mentioned above, the declaration must state that the size of the array is five. The declaration of this array, named numbers, is as follows:
int numbers[5];
The size of an array must be an integer. A size of 3.5, for example, cannot be used as it is not possible to have half an integer. Also, as the size of an array tends to be used throughout a program, it is common to define a symbolic constant for the array size:
#define SIZE 5
int numbers[SIZE];
The symbolic constant definition should be placed above main(), as usual, and the array declaration placed within main().
Memory Allocation
The RAM allocated as a result of an array declaration is large enough to store all the values indicated by the size. The memory is also arranged in one contiguous block. A conceptual picture of the memory allocated for the numbers array is as follows:
Each location in an array capable of storing a value is called an element. Each element is identified by an integer called an index or subscript. In C++, the smallest subscript value is always zero. An array’s largest subscript value is the size of the array minus one. Since the numbers array has a size of five, it has five elements numbered zero through four. Note that an array never has an element with a subscript value equal to the size of the array.
Using Array Elements
An element is used in the same manner as a variable of the same data type is used. For example, since the numbers array is an array of integers, each element is used just like any other integer variable is used. The only real difference is using an element requires identifying it by its subscript value. Here are two array declarations and examples which use elements from each array for different purposes:
double prices[10];
char letters[7];
| Example | Explanation |
|---|---|
prices[4] = 2.75; | Assign 2.75 to the fifth element of the prices array. |
letters[6] = 'x'; | Assign a lowercase 'x' to the last element of the letters array. |
std::cin >> prices[0]; | Read a typed value into the first element of prices. |
prices[8] = 5.99 * 3; | Assign the result of a calculation to the ninth element of prices. |
prices[1] = prices[0] * 2; | Multiply the value stored in the first element of prices by two and store the result in the second element of prices. The first element’s value is unchanged. |
std::cout << letters[6]; | Display the value in the last element of letters. |
total = prices[1] + taxes; | Add the value in the second element of prices to the value of the taxes variable and assign the result to the variable total. |
A subscript value must be an integer, or an expression which evaluates to an integer, and must be valid. The number 2.4 cannot be used as a subscript because it is not an integer. If an attempt is made to use a non-integer value as a subscript, the program will not compile.
The number 10 is an example of an invalid subscript value for the prices and letters arrays because it is larger than both arrays’ largest subscript value. No check is performed, however, to ensure valid subscript values are used. It is the programmer’s responsibility to ensure they are valid. If 10 is accidentally used, a run-time or logic error could result.
Arrays and Loops
As can be seen in the examples above, each element in an array can be accessed individually and different actions taken with each. In many cases, however, programs perform the same action with all an array’s elements. Perhaps seven numbers entered by the user will be read into an array’s seven elements, or maybe all values in an array will be displayed on the screen. In these cases, each element of an array is accessed from the start to the end of the array. The subscript values are counted through from zero to the size of the array minus one and the same action is performed with each array element. Sounds like a loop and a counter are needed.
A for loop is frequently used with arrays because it is a natural choice when a counter-controlled loop is needed. Here is an example that shows a for loop being used to display the values in the numbers array (assume each element has a value):
for (counter = 0; counter < 5; counter++) {
std::cout << numbers[counter] << std::endl;
}
Step through the code. Note that the subscript value used to access an element is stored in a variable. What must be the data type of counter?
A single program may need to loop through an array multiple times for different purposes. Symbolic constants are frequently used, rather than literal values, wherever the size of an array is needed.
Initialization
When a variable is declared its value is undefined, or garbage, unless it is initialized. This is true of the elements of an array as well. If an initial value is desired for each element of an array at the time it is declared, an initializer list can be used in its declaration. The general form of an array declaration with an initializer list is as follows:
data-type array-name[size] = {value1, value2, ...};
An initializer list consists of a comma separated list of values (aka initializers) within braces. The following initializer list assigns the values 4, 8, 2, 19, and 0, in this order, to the elements of the numbers array:
int numbers[5] = {4, 8, 2, 19, 0};
If the list contains more values than elements, the program will not compile. If the list contains fewer values than elements, the values provided will be assigned to the elements at the beginning of the array and the remaining elements assigned values of zero. For example, if only 4 and 8 are in the initializer list in the previous example, 4 would be assigned to the first element, 8 assigned to the second element, and the remaining three elements assigned values of 0. What is the result of an initializer list containing a single value of zero?
A loop can be used as an alternative to assigning initial values to array elements:
for (counter = 0; counter < 5; counter++) {
numbers[counter] = 0;
}
Note that values are not assigned at the time the array is declared.