Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 415

13


20 elements instead of 25, you have to change several lines of code. If you used a con-
stant, you only have to change the value of your constant.
Creating the number of elements, or dimension size, with an enumeration is a little dif-
ferent. Listing 13.3 illustrates this by creating an array that holds values—one for each
day of the week.

LISTING13.3 Using constsand enumsin Arrays


0: // Listing 13.3
1: // Dimensioning arrays with consts and enumerations
2:
3: #include <iostream>
4: int main()
5: {
6: enum WeekDays { Sun, Mon, Tue,
7: Wed, Thu, Fri, Sat, DaysInWeek };
8: int ArrayWeek[DaysInWeek] = { 10, 20, 30, 40, 50, 60, 70 };
9:
10: std::cout << “The value at Tuesday is: “ << ArrayWeek[Tue];
11: return 0;
12: }

The value at Tuesday is: 30

Line 6 creates an enumeration called WeekDays. It has eight members. Sunday is
equal to 0, and DaysInWeekis equal to 7. On line 8, an array called ArrayWeekis
declared to have DaysInWeekelements, which is 7.
Line 10 uses the enumerated constant Tueas an offset into the array. Because Tueevalu-
ates to 2 , the third element of the array,ArrayWeek[2], is returned and printed on line 10.

OUTPUT


ANALYSIS

Arrays
To declare an array, write the type of object stored, followed by the name of the array
and a subscript with the number of objects to be held in the array.
Example 1
int MyIntegerArray[90];
Example 2
long * ArrayOfPointersToLongs[100];
To access members of the array, use the subscript operator.
Free download pdf