Chapter 15
In This Chapter
Expanding simple variables into an array
Comparing the array to a rental car lot
Indexing into an array
Initializing an array
The variables declared so far have been of different types with different sizes and capabilities. Even so, each variable has been capable of holding only a single value at a time. If I wanted to hold three numbers, I had to declare three different variables. The problem is that there are times when I want to hold a set of numbers that are somehow closely related. Storing them in variables with names that bear some similarity of spelling such as nArg1, nArg2, and so on may create associations in my mind but not for poor, ignorant C++.
There is another class of variable known as the array that can hold a series of values. Arrays are the subject of this chapter and the next chapter. (Here I present arrays in general. In the next chapter, I look at the particular case of the character array.)
You may think of a variable as a truck. There are small trucks, like a short int, capable of holding only a small value; and there are larger trucks, like a long double, capable of holding astoundingly large numbers. However, each of these trucks can hold only a single value.
Each truck has a unique designator. Perhaps you give your vehicles names, but even if you don’t, each has a license plate that uniquely describes each of your vehicles, at least within a given state.
This works fine for a single family. Even the largest families don’t have so many cars that this arrangement gets confusing. But think about an auto rental agency. What if they referred to their cars solely by a license plate number or some other ID? (Boy, just thinking about that Hertz!)
After filling out the myriad forms — including deciding whether I want the full insurance coverage and whether I’m too lazy to fill it up with gas before I bring it back — the guy behind the counter says, “Your car is QZX123.” Upon leaving the building and walking to the parking lot, I look over a sea of cars that rival a Wal-Mart parking lot. Exactly where is QZX123?
That’s why the guy behind the counter actually says something quite different. He says something like, “Your car is in slot B11.” This means that I am to skip past row A directly to row B and then start scanning down the line for the eleventh car from the end. The numbers are generally painted on the pavement to help me out, but even if they weren’t visible, I could probably figure out which car he meant.
Several things have to be true in order for this system to work:
That’s pretty much the way arrays work. I can give a series of numbers a single name. I refer to individual numbers within the series by index. So the variable x may refer to a whole series of whole numbers, x(1) would be the first number in the series, x(2) the second, and so on in sequence, just like the cars at the rental agency.
To declare an array in C++, you must provide the name, type, and number of elements in the array. The syntax is as follows:
int nScores[100];
This declares an array of 100 integers and gives them the name nScores.
You must provide an index to access a specific element within the array. An index must be a counting type (such as int), as demonstrated here:
nScores[11] = 10;
This is akin to the way that rental cars are numbered. However, unlike humans, C++ starts with 0 when numbering its arrays. Thus the first score in the array nScores is nScores[0].
So how does this work exactly? Well, return to the rental car lot one more time (for the last time, I promise). Figure 15-1 shows how rental cars are typically numbered in their parking lots. The first car in row B carries the designation B1. To find B11, I simply move my gaze ten cars to the right.
C++ does a similar thing. To execute the statement nScores[11] = 10, C++ starts with the address of the first element in nScores. It then moves to the right 11 spaces and stores a 10 at that location. This is shown graphically in Figure 15-2. (I say a lot more about what it means to “take the address of the first element” in the next three chapters. Please just accept the statement for now.)
int nScores[100];
declares 100 scores, which are numbered from 0 to 99. The expression
nScores[100] = 0; // this is an error
zeroes out the first element beyond the end of the array. The last element in the array is nScores[99]. The C++ compiler will not catch this error and will happily access this non-element, which very often leads to the program accessing some other variable by mistake. This type of error is very hard to find because the results are so unpredictable.
The following example averages a set of scores and then displays that average. However, unlike earlier demonstrations, this program retains the scores’ input in an array that it can then output along with the average.
//
// ArrayDemo - demonstrate the use of an array
// to accumulate a sequence of numbers
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// displayArray - displays the contents of the array
// of values of length nCount
void displayArray(int nValues[100], int nCount)
{
for(int i = 0; i < nCount; i++)
{
cout.width(3);
cout << i << " - " << nValues[i] << endl;
}
}
// averageArray - averages the contents of an array
// of values of length nCount
int averageArray(int nValues[100], int nCount)
{
int nSum = 0;
for(int i = 0; i < nCount; i++)
{
nSum += nValues[i];
}
return nSum / nCount;
}
int main(int nNumberofArgs, char* pszArgs[])
{
int nScores[100];
int nCount;
// prompt the user for input
cout << "This program averages a set of scores
"
<< "Enter scores to average
"
<< "(enter a negative value to terminate input"
<< endl;
for(nCount = 0; nCount < 100; nCount++)
{
cout << "Next: ";
cin >> nScores[nCount];
if (nScores[nCount] < 0)
{
break;
}
}
// now output the results
cout << "Input terminated." << endl;
cout << "Input data:" << endl;
displayArray(nScores, nCount);
cout << "The average is "
<< averageArray(nScores, nCount)
<< endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '
'),
cin.get();
return 0;
}
This program starts at the beginning of main() by prompting the user for a series of integer values. The program saves each of the numbers that the user inputs into the array nScores in a loop. The program exits the loop as soon as the user enters a negative number.
Once the user has either entered a negative value or 100 values in a row, the program exits the loop. Now the nScores array contains all of the numbers entered, and nCount contains a count of the number of values that are stored in the array.
The program then calls the function displayArray() to echo to the user the values entered. Finally, the function averageArray() returns the integer average of the numbers entered.
The displayAverage() function iterates through the values in the array passed it, displaying each value in turn. The averageArray() function works by also iterating through the array nValues, accumulating the sum of the array’s elements in a local variable nSum. The function returns nSum / nCount, which is the average of the values in nValues.
In practice, the output of the program appears as follows:
This program averages a set of scores
Enter scores to average
(enter a negative value to terminate input
Next: 10
Next: 20
Next: 30
Next: 40
Next: 50
Next: -1
Input terminated.
Input data:
0 - 10
1 - 20
2 - 30
3 - 40
4 - 50
The average is 30
Press Enter to continue …
Like any other variable, an array starts out with an indeterminate value if you don’t initialize it. The only difference is that unlike a simple variable, which contains only one undetermined value, an array starts out with a whole lot of unknown values:
int nScores[100]; // none of the values in nScores
// known until you initialize them
You can initialize the elements of an array with a loop as follows:
int nScores[100]; // declare the array and then...
for (int i = 0; i < 100; i++) // ...initialize it
{
nScores[i] = 0;
}
You can also initialize an array when you declare it by including the initial values in braces after the declaration. For a small array, this is easy:
int nCount[5] = {0, 1, 2, 3, 4};
Here I initialized the value of nCount[0] to 0, nCount[1] to 1, nCount[2] to 2, and so on. If there are more elements than numbers in the list, C++ pads the list with zeros. Thus, in the following case:
int nCount[5] = {1};
the first element (nCount[0]) is set to 1. Every other element gets initialized to zero. You can use this approach to initialize a large array to zero as well:
int nScores[100] = {0};
This not only declares the array but initializes every element in the array to zero.
By the same token, you don’t have to provide an array size if you have an initializer list — C++ will just count the number of elements in the list and make the array that size:
int nCount[] = {1, 2, 3, 4, 5};
This declares nCount to be 5 elements large because that’s how many values there are in the initializer list.
3.135.188.121