An array
is a contiguous group of memory locations that all have the same type. To refer to a particular location or element in the array
, we specify the name of the array
and the position number of the particular element in the array
.
Figure 7.1 shows an integer array
called c
that contains 12 elements. You refer to any one of these elements by giving the array
name followed by the particular element’s position number in square brackets ([]
). The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array
). The first element has subscript 0 (zero) and is sometimes called the zeroth element. Thus, the elements of array c
are c[0]
(pronounced “c
sub zero”), c[1]
, c[2]
and so on. The highest subscript in array c
is 11, which is 1 less than the number of elements in the array
(12). array
names follow the same conventions as other variable names.
A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that variable a
is equal to 5
and that variable b
is equal to 6
, then the statement
c[ a + b ] += 2;
adds 2 to array
element c[11]
. A subscripted array
name is an lvalue—it can be used on the left side of an assignment, just as non-array
variable names can.
Let’s examine array c
in Fig. 7.1 more closely. The name of the entire array
is c
. Each array
knows its own size, which can be determined by calling its size member function as in c.size()
. Its 12 elements are referred to as c[0]
to c[11]
. The value of c[0]
is -45
, the value of c[7]
is 62
and the value of c[11]
is 78
. To print the sum of the values contained in the first three elements of array c
, we’d write
cout << c[ 0 ] + c[ 1 ] + c[ 2 ] << endl;
To divide the value of c[6]
by 2
and assign the result to the variable x
, we would write
x = c[ 6 ] / 2;
The brackets that enclose a subscript are actually an operator that has the same precedence as parentheses. Figure 7.2 shows the precedence and associativity of the operators introduced so far. The operators are shown top to bottom in decreasing order of precedence with their associativity and type.