Sams Teach Yourself C++ in 21 Days

(singke) #1
5: {
6: int SomeArray[2][5] = { {0,1,2,3,4}, {0,2,4,6,8}};
7: for (int i = 0; i<2; i++)
8: {
9: for (int j=0; j<5; j++)
10: {
11: cout << “SomeArray[“ << i << “][“ << j << “]: “;
12: cout << SomeArray[i][j]<< endl;
13: }
14: }
15: return 0;
16: }

SomeArray[0][0]: 0
SomeArray[0][1]: 1
SomeArray[0][2]: 2
SomeArray[0][3]: 3
SomeArray[0][4]: 4
SomeArray[1][0]: 0
SomeArray[1][1]: 2
SomeArray[1][2]: 4
SomeArray[1][3]: 6
SomeArray[1][4]: 8
Line 6 declaresSomeArrayto be a two-dimensional array. The first dimension
indicates that there will be two sets; the second dimension consists of five inte-
gers. This creates a 2×5 grid, as Figure 13.4 shows.

OUTPUT


420 Day 13


LISTING13.5 continued

ANALYSIS

FIGURE13.4
A 2×5 array.

0

1

2 3

4

0
Some Array [5] [2]

1

2 3

4

The values are based on the two sets of numbers. The first set is the original numbers;
the second set is the doubled numbers. In this listing, the values are simply set, although
they could be computed as well. Lines 7 and 9 create a nested forloop. The outer for
loop (starting on line 7) ticks through each member of the first dimension, which is each
of the two sets of integers. For every member in that dimension, the inner forloop (start-
ing on line 9) ticks through each member of the second dimension. This is consistent
with the printout. SomeArray[0][0]is followed by SomeArray[0][1]. The first
Free download pdf