Declaring and Using Arrays


An array is a variable. Just like other kinds of variables, your programs must declare arrays to use them. Array declarations must have a data type, a variable name, and a pair of square brackets that usually contain the size of the array. For example, if you want to declare an array of integers, the declaration would be similar to this:

 int thisArray[10]; 


The statement int specifies the data type. The name of the array is thisArray, and its size is 10, which means it holds 10 integers. Most programmers call the number in the square brackets of the declaration the size specifier. Figure 10.2 illustrates this array.

Figure 10.2. An array of 10 elements.


Note

Programmers call the array element number its subscript. When they read statements such as thisArray[0], thisArray[1], and so forth, they read them as "this array sub zero, this array sub one," and so on. Somewhat confusingly, array subscript numbers are also referred to as array index numbers.


Every element in an array is numbered. To continue the mailbox analogy, the array element number is essentially the address of the element. Array element numbering always starts with 0 (zero). To access an element in an array, your program specifies the array name followed by the element number in square brackets. If your program needs to access the first element in the array, it specifies array location 0, like this:

 thisArray[0] = 5; 


This statement stores a 5 in the first location in the array, which is location number 0. To store a value in the tenth array element, you store it in array location number 9:

 thisArray[9] = -20; 


Pop quiz. If you want to store a value in the fifth element, what location is that?

Answer: The fifth element in the array is in location number 4. This is how you would write it in your code.

 thisArray[4] = 10; 


It may be confusing at first that the fifth element in an array is numbered 4 rather than 5. However, as you work with arrays, you'll quickly get used to it.

To retrieve a value from an array, you just put the array to the right of an equal sign, like so:

 int thisInt = thisArray[4]; 


When you first start working with arrays, it's easy to get the terminology mixed up. For instance, the two statements below both contain numbers in square brackets.

 int thisArray[10]; thisArray[9] = -20; 


The first statement shown here is the declaration of the array. The 10 in the square brackets is the size specifier for the array. It tells how many integers the array can hold. However, the 9 in the second statement is not a size specifier. It is a subscript. It tells which array location the -20 is to be stored in.

Why Does Array Numbering Start with 0?

When I was teaching college-level C++ programming classes, my students would often wonder why C++ array numbering starts with 0 rather than 1. There is actually a very good reason.

C++ array numbering starts with 0 because the array name actually holds the address of the start of the array. The starting address of the array is called the array's base address.

To access a particular array element, the executable version of your program contains code that adds the element number to the array's starting address. The compiler generates this code. You never see it in your source code, but that's what's going on behind the scenes.

When your program needs to access the first array element, it contains a statement such as the following:

 thisArray[0] = 5; 


The compiler generates executable code that adds the element number, which is 0, to the address of the array. It then stores the 5 at that location.

To access the second, third, or fourth elements, the compiler generates executable code that adds 1, 2, or 3 to the base address.

Because the element or subscript numbers are added to the base address of an array, they can also be referred to as offset numbers. The technique of using a base address and offset number to access array elements is extremely efficient. It is one of the features that make C++ programs so fast.


Warning

Even though array size specifiers and subscript numbers both appear in square brackets, they are two different things that serve two different purposes.


You can use an array of integers anywhere you would use an integer. Let's demonstrate with a small sample program.

Listing 10.1. Using an array in a program

 1     #include <cstdlib> 2     #include <iostream> 3 4     using namespace std; 5 6     int main(int argc, char *argv[]) 7     { 8        int thisArray[10]; 9        int i; 10 11       i = 0; 12       while (i<10) 13       { 14      thisArray[i] = 10-i; 15      i++; 16       } 17 18       i=0; 19       while (i<10) 20       { 21         cout << thisArray[i]; 22         cout << endl; 23         i++; 24       } 25 26       system("PAUSE"); 27 28       i=9; 29       while (i>=0) 30       { 31      cout << thisArray[i]; 32      cout << endl; 33      i--; 34       } 35 36       system("PAUSE"); 37       return EXIT_SUCCESS; 38    } 

This is a short console program, similar to the ones you wrote in the first few chapters of this book. It declares an array on line 8. The program next declares a loop counter variable called i. On line 11, the program sets i to 0.

Tip

If you can't remember how to compile a console program, you can access instructions for compiling by inserting the CD that comes with this book into your CD-ROM drive. Your computer will automatically display the Welcome page for the CD. On the Welcome page is a link to instructions for compiling all of the sample programs.


Next, the program enters a loop on line 12. In the loop, the program stores values in thisArray. The first time through the loop, i is 0, so the statement on line 14 stores the value 10 (the result of 10 0) in thisArray[0]. The second time through the loop, i is 1, so the statement on line 14 stores the value 9 (the result of 10 1) in thisArray[1]. It continues in this manner until i is 10. Figure 10.3 shows the result of the loop on lines 1216.

Figure 10.3. Storing numbers in an array.


After the program fills the array, it pauses until the user presses a key. It then enters another loop on line 19 that prints each array element one by one. The first time through this loop, it prints the 10 stored in thisArray[0]. The next time through the loop, the program prints the 9 stored in thisArray[1], and so on. When the loop exits, the program pauses again.

After the user presses a key, the program sets i to 9 and starts another loop on line 29. In this loop, i starts at 9 and gets decremented each time through the loop until it gets to -1, and then the loop quits. The statements on lines 3132 print the contents of the current array location followed by an endline. Using this loop, the program prints the values 1 through 10.

2D Arrays

The array you saw in Listing 10.1 was one-dimensional. When you use arrays, you can expand them into higher dimensions. This is not as odd as it sounds at first. If you think of a one-dimensional array as a row of data, as shown back in Figure 10.3, then creating a two-dimensional array is just a matter of adding more rows. In fact, you can think of a 2D array as a table, as Figure 10.4 illustrates.

Figure 10.4. A 2D array.


The 2D array of integers in Figure 10.4 is shown as a table with 3 rows and 10 columns. Many programmers like to think of a 2D array as having a height and width. The height is the number of rows, and the width is the number of columns.

Your program declares a 2D array by simply adding the extra dimension to an array declaration. Here's how to declare the array shown in Figure 10.4:

 int thisArray[3][10]; 


The integer array thisArray contains 3 rows. Each row holds 10 integers. Another way to say that is that the array has 3 rows and 10 columns.

Note

Two-dimensional arrays in C++ do not really have rows and columns. It's just convenient to think of them as if they do.


Accessing elements in a 2D array is similar using a one-dimensional array. For example, if I wanted to store the number 5 in the second location of the third row, I would use a statement like this:

 thisArray[2][1] = 5; 


Of course the third row in the array is numbered 2 because array numbering starts with 0. For the same reason, the second location in row number 2 (the third row) is numbered 1.

Let's look at a quick example of using 2D arrays (Listing 10.2). I'll revise the program from Listing 10.1 so that it uses a 2D array rather than a one-dimensional array.

Listing 10.2. Using a 2D array in a program

 1      #include <cstdlib> 2      #include <iostream> 3 4      using namespace std; 5 6      int main(int argc, char *argv[]) 7      { 8          int thisArray[3][10]; 9          int i,j; 10 11         i = 0; 12         while (i<3) 13         { 14            j = 0; 15            while (j<10) 16            { 17                thisArray[i][j] = (i*j) + (i+j); 18    j++; 19        } 20                i++; 21          } 22 23          i = 0; 24          while (i<3) 25          { 26             j = 0; 27           while (j<10) 28           { 29        cout << thisArray[i][j]; 30             if (thisArray[i][j]<10) 31        { 32            cout << " "; 33             } 34             else 35             { 36                cout << " "; 37             } 38             j++; 39          } 40          cout << endl; 41          i++; 42       } 43 44       system("PAUSE"); 45 46       return EXIT_SUCCESS; 47    } 

The program in Listing 10.2 declares a 2D array on line 8. It also declares two integer variables it uses as loop counters. On line 12 it enters its first loop. This loop iterates through each row. It contains another loop on lines 1519 that iterates through each column.

The first time through this pair of loops, both i and j are 0, so the program stores a 0 in row 0, column 0. Next, line 18 increments j to 1. The inner loop repeats because j is less than 10. On line 17, the program stores a 1 in row 0, column 1. The inner loop continues iterating until it has executed once for each column in row 0. At that point, j equals 10, so the inner loop ends. Line 20 increments i to 1 and the outer loop repeats. Line 14 sets j back to 0 and the inner loop executes 10 more times, once for each column in row 1. The process repeats again for row 2.

The statements on lines 2342 use the same loop structure to enable the program to iterate through the 2D array again. As it does, it prints the value in each array location, followed by some spaces. The if-else statement on lines 3037 put either one or two spaces between the printed numbers. This enables the program to line up the output nicely. Figure 10.5 shows the output from this program.

Figure 10.5. The output from the program in Listing 10.2.


3D Arrays

You can also extend array declarations into three dimensions. Programmers often say that 3D arrays have height, width, and depth. It's rather like layering 2D arrays one on top of anotheryou can think of it like multiple tables (or spreadsheets from a spreadsheet program) laid one on top of another. Here's the declaration of a 3D array:

 int thisArray[3][10][5]; 


In this declaration, the array thisArray can be thought of as a group of 10x5 tables. The stack of tables is three deep. Listing 10.3 gives a version of the program from Listing 10.2 that uses a 3D array.

Listing 10.3. Using a 2D array in a program

 1    #include <cstdlib> 2    #include <iostream> 3 4    using namespace std; 5 6    int main(int argc, char *argv[]) 7    { 8    int thisArray[3][10][5]; 9    int i,j,k; 10 11   i = 0; 12   while (i<3) 13   { 14     j = 0; 15     while (j<10) 16     { 17        k = 0; 18        while (k<5) 19        { 20            thisArray[i][j][k] = (i*j*k) + (i+j+k); 21            k++; 22        } 23          j++; 24      } 25       i++; 26   } 27 28   i = 0; 29   while (i<3) 30   { 31      j = 0; 32      while (j<10) 33      { 34        k = 0; 35        while (k<5) 36        { 37            cout << thisArray[i][j][k]; 38       if (thisArray[i][j][k]<10) 39             { 40                 cout << " "; 41             } 42             else 43             { 44                cout << " "; 45             } 46             k++; 47          } 48          j++; 49          cout << endl; 50       } 51         i++; 52       } 53 54       system("PAUSE"); 55 56       return EXIT_SUCCESS; 57    } 

The program in Listing 10.3 uses three nested loops on lines 1226 to iterate through the 3D array. These loops store values in the array. Another group of three nested loops on lines 2952 print the values in the array.

Can I Make Arrays with More than Three Dimensions?

The C++ language supports arrays in more dimensions than three. The maximum number of array dimensions is determined by whoever writes the compiler you're using. Most programmers never use more than three dimensions in their arrays. In fact, the vast majority of programmers seldom use more than two array dimensions. Therefore, if you become comfortable using arrays of one, two, and three dimensions, you will know what you need to for game programming.

A few high-end methods of graphics programming use 4D arrays. Four-dimensional arrays are typically only used for very accurate collision detection or extremely high-end rendering (a technique called volumetric rendering). However, programming techniques involving 4D arrays are not usually needed in games. Instead, they are implemented in applications such as professional flight simulators that are used to train pilots. Such applications run on specialized hardware that generally costs millions of dollars.




Creating Games in C++(c) A Step-by-Step Guide
Creating Games in C++: A Step-by-Step Guide
ISBN: 0735714347
EAN: 2147483647
Year: N/A
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net