Accessing Array Elements. Sams Publishing Object-Oriented Programming in C++
Реклама
Реклама
08 3087 CH07 11/29/01 2:14 PM Page 267
Arrays and Strings
267
Notice that the first array element is numbered 0. Thus, since there are four elements, the last one is number 3. This is a potentially confusing situation; you might think the last element in a four-element array would be number 4, but it’s not.
Accessing Array Elements
In the
REPLAY example we access each array element twice. The first time, we insert a value into the array, with the line cin >> age[j];
The second time, we read it out with the line cout << “\nYou entered “ << age[j];
In both cases the expression for the array element is age[j]
This consists of the name of the array, followed by brackets delimiting a variable j. Which of the four array elements is specified by this expression depends on the value of j
; age[0] refers to the first element, age[1] to the second, age[2] to the third, and age[3] to the fourth. The variable (or constant) in the brackets is called the array index.
Since j is the loop variable in both for loops, it starts at 0 and is incremented until it reaches
3, thereby accessing each of the array elements in turn.
Averaging Array Elements
Here’s another example of an array at work. This one,
SALES
, invites the user to enter a series of six values representing widget sales for each day of the week (excluding Sunday), and then calculates the average of these values. We use an array of type double so that monetary values can be entered.
// sales.cpp
// averages a weeks’s widget sales (6 days)
#include <iostream> using namespace std; int main()
{ const int SIZE = 6; //size of array double sales[SIZE]; //array of 6 variables cout << “Enter widget sales for 6 days\n”; for(int j=0; j<SIZE; j++) //put figures in array cin >> sales[j];
7
Изтегляне
Реклама