|
|
|
|
|
|
|
declares an array of 25 long integers, named LongArray. When the compiler sees this declaration, it sets aside enough memory to hold all 25 elements. Because each long integer requires 4 bytes, this declaration sets aside 100 contiguous bytes of memory, as illustrated in Figure 15.1. |
|
|
|
|
|
|
|
|
FIGURE 15.1
Declaring an array. |
|
|
|
|
|
|
|
|
You access each of the array elements by referring to an offset from the array name. Array elements are counted from 0; therefore, the first array element is arrayName[0]. In the LongArray example, LongArray[0] is the first array element, LongArray[1] the second, and so forth. |
|
|
|
|
|
|
|
|
This can be somewhat confusing. The array SomeArray[3] has three elements: SomeArray[0], SomeArray[1], and SomeArray[2]. More Generally, SomeArray[n] has n elements that are numbered SomeArray[0] through SomeArray[n-1]. |
|
|
|
|
|
|
|
|
Therefore, LongArray[25] is numbered from LongArray[0] through LongArray[24]. Listing 15.1 shows how to declare an array of five integers and fill each with a value. |
|
|
|
|
|
|
|
|
LISTING 15.1 USING AN INTEGER ARRAY |
|
|
|
 |
|
|
|
|
1: //Listing 15.1 - Arrays
2: #include <iostream.h>
3:
4: int main()
5: {
6: int myArray[5];
7: int i;
8: for (i=0; i<5; i++) // 04
9: {
10: cout << Value for myArray[ << i << ]: ;
11: cin >> myArray[i];
12: }
13: for (i = 0; i<5; i++) |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|