< previous page page_226 next page >

Page 226
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.
10905-0226a.gif
FIGURE 15.1
Declaring an array.
Array Elements.
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

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 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++)
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_226 next page >

If you like this book, buy it!